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

前端 未结 3 1788
长情又很酷
长情又很酷 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.

提交回复
热议问题