What is the best practice for managing the MongoServer class life cycle? Should I create one and close it at the end of each request or should it be kept as a singleton for the entire life of the app using something like StructureMap?
Any help is appreciate.
MongoDB configuration Even MongoDB itself has an option to limit the maximum number of incoming connections. It defaults to 64k.
Configuring an ASP.NET Core Project with MongoDB For the rest of the example, we are going to continue using the local server keeping in mind that all the actions performed on the local server can be done on the Atlas dashboard. We intentionally named the class properties the same as the fields in the appsettings.
There is no official MongoDb provider implementation for EF core at this time, I did not see any mention of MongoDb in the . net core 7 (the next version) roadmap as of now.
In the official documentation it is stated that MongoServer
, MongoDatabase
, and MongoCollection
are thread safe, and that you're supposed to create one single MongoServer
for each database that you connect to.
Thus, MongoServer
, MongoDatabase
, and MongoCollection
can safely be configured to be singletons. MongoServer
will even help enforcing this by returning the same MongoDatabase
instance for successive calls, and MongoDatabase
will do the same thing for MongoCollection
s.
I.e. your MongoServer
instance can safely be configured to have a singleton lifestyle in your IoC container, and you might as well set up injection for MongoDatabase
and maybe even MongoCollection
as well.
I'm using this strategy with Windsor myself - you can see my MongoInstaller
here: https://gist.github.com/2427676 - it allows my classes to just go ahead and do this:
public class SomeClass { public SomeClass(MongoCollection<Person> people) { ... } }
in order to have a collection injected, nice and ready to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With