MongoDB 连接方法 c#

MongoDB connection methods c#

我在 ASP.NET C# Web API 中使用 MongoDB。当我参考 MongoDB 文档时,我发现连接是自动打开和关闭的。

A MongoClient object will be the root object. It is thread-safe and is all that is needed to handle connecting to servers, monitoring servers, and performing operations against those servers. [...] It is recommended to store a MongoClient instance in a global place, either as a static variable or in an IoC container with a singleton lifetime. However, multiple MongoClient instances created with the same settings will utilize the same connection pools underneath.

我无法真正理解存储实例或在具有单例生命周期的 IOC 容器中的含义。

我能得到任何解释如何做到这一点的参考资料吗?直接在我的 CRUD 操作上使用 new MongoClient() 不好吗?我真的必须管理这些连接吗?我是否必须在代码中处理某些内容才能在 MongoDB 中实现线程安全?

我问这个是因为我的写入和删除操作在多线程上以错误的顺序执行。

如果您需要更多代码,请随时询问。

Is It bad to just use new MongoClient()

不,这种方法没有任何问题,但它不再被认为是可取的。事实上,当您创建一个 MongoClient 时,内部客户端的逻辑会检查您之前是否已经使用相同的 MongoClientSettings 创建了一个 MongoClient,如果是,那么您将重用之前创建的客户端。所以实际上这个逻辑是单例的,但它是在 mongoClient 端实现的。但是,这种方法也有一些缺点,请查看此 doc 了解详细信息。

Do I have to really manage these connections?

不,这是 MongoClient 的职责。

And do I have to handle something in code to achieve thread safety in MongoDB?

不,您不需要做任何事情,但是,即使 MongoClient 中的一些底层功能是线程安全的,但并非 MongoClient 提供的所有功能都是线程安全的,例如会话不是线程安全的。