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

Roman picture Roman · Apr 20, 2012 · Viewed 9.7k times · Source

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.

Answer

mookid8000 picture mookid8000 · Apr 20, 2012

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.