简体   繁体   中英

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.

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.

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

The C# driver manages connections to the server automatically (it uses a connection pool). There is no need to call server.Connect as the driver connects automatically. Don't call server.Disconnect as that closes all connections in the connection pool and interferes with efficient connection pooling.

As far as managing the lifecycle of the MongoServer instance you are free to store it in a static variable and use it for the lifetime of your process (and share it across threads, it is thread-safe). Alternatively, you can just call MongoServer.Create again whenever you need to get the server instance. As long as you keep calling MongoServer.Create with the same connection string you will keep getting back the same MongoServer instance.

使用任何IOC容器(结构图,温莎等)注入它,并根据请求保持其生命周期。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM