Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way to manage MongoDB connections in ASP.Net MVC?

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.

like image 274
Roman Avatar asked Apr 20 '12 06:04

Roman


People also ask

How many connections MongoDB can handle?

MongoDB configuration Even MongoDB itself has an option to limit the maximum number of incoming connections. It defaults to 64k.

Can we use MongoDB with ASP NET?

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.

Does EF core support MongoDB?

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.


1 Answers

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 MongoCollections.

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.

like image 170
mookid8000 Avatar answered Sep 19 '22 11:09

mookid8000