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

前端 未结 3 1778
长情又很酷
长情又很酷 2021-02-01 17:01

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

相关标签:
3条回答
  • 2021-02-01 17:22

    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.

    0 讨论(0)
  • 2021-02-01 17:29

    Inject it using any IOC container (structuremap, Windsor etc.) and keep its lifetime to be on per request basis.

    0 讨论(0)
  • 2021-02-01 17:35

    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.

    0 讨论(0)
提交回复
热议问题