Tag Archives: .net mongodb

Disconnecting with the MongoDB .NET Driver

The MongoDB .NET Driver has a public method called Disconnect on the MongoServer class.  This method is somewhat useful in certain contexts such as when the server is shutting down or the application is exiting.  However, it is extremely important to know what this method does before using it because it could kill your application.

The documentation simple states that this causes the server to disconnect from the server.  In other words, this method terminates all connections to all the servers and shuts down any in flight operations.  This isn’t your standard ADO.NET Connection at all.  In fact, MongoServer isn’t a connection at all, but rather a proxy to 1 or more mongod or mongos processes.

In addition, the documented way to get access to a MongoServer is to use a static Create method.  MongoServer.Create() and all it’s overloads actually return the same instance when the specified connection settings match a previously created MongoServer.  Therefore, the documented behavior of Disconnect is even more unexpected when this information gets factored in.

There is a good reason for this method.  It cleanly disposes of all the resources associated with the many connections and sockets it manages.  So it’s useful when an application is exiting or the OS is shutting down.  However, most people call Disconnect because it’s there and it seems like the right thing to do.

We’ve started working on the next version (2.0) of the driver and are working through some issues, such as this one, to clean up and correct so that the api matches expectations and to make it much more difficult to do the wrong thing.