I am using MongoDB in my ASP.NET C# Web API. When I reference MongoDB docs I found out that the connections are opened and closed automatically.
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.
I couldn't really understand what it meant by storing instance or in IOC container with singleton lifetime.
Can I get any reference explaining how to do that ? Is It bad to just use new MongoClient()
directly on my CRUD operations. Do I have to really manage these connections? And do I have to handle something in code to achieve thread safety in MongoDB?
I am asking this because my write and delete operation is getting executed in the wrong order on multithreads.
If you need more code please feel free to ask.
CodePudding user response:
Is It bad to just use new MongoClient()
no, there is nothing wrong in this approach, but it's no longer considered as preferable. In fact when you create a MongoClient, the internal client's logic checks whether you already created a MongoClient with the same MongoClientSettings before and if so, then you will just reuse the previously created client. So effectively this logic is singleton, but it's implemented on the mongoClient side. However there are some down sides with this approach, look at this doc for details.
Do I have to really manage these connections?
no, this is MongoClient responsibility.
And do I have to handle something in code to achieve thread safety in MongoDB?
no, you don't need to do anything, however, even though some underlying functionality in MongoClient is thread safe, not all functionality provided by MongoClient is thread safe, for example sessions are not thread safe.