Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properly shutting down MongoDB database connection from C# 2.1 driver?

Tags:

c#

mongodb

I am just getting started with integrating MongoDB into my application and I have ran into a few questions. In my application I am using the newest 2.1 version of the MongoDB C# driver and only using MongoDB for application logging.

Currently before showing my main application Form I first check to see if mongod.exe is running and if not I start it. Then when my main Form is shown it opens a connection to the database for use seen below.

public void Open()
{
    Client = new MongoClient("mongodb://localhost:27017");
    Database = Client.GetDatabase(DBName);
    Collection = Database.GetCollection<BsonDocument>(ColName);
}

My question is how I should properly shutdown this connection when my application is closing?

Also are there in considerations I should take into account in leaving mongod.exe running versus exiting it each time the application closes?

I have searched a few times trying to figure out if there is a proper way to shutdown the connection but have found nothing very specific. There is an old SO post (that I can't seem to find now) mentioning a .Dispose method, though I cannot seem to find it in the newest driver nor from my IDE's auto complete.

like image 394
KDecker Avatar asked Sep 21 '15 19:09

KDecker


1 Answers

As of today's version of MongoDB (v2.0.1.27 for MongoDB.Driver), there's no need to close or dispose of connections. The client handles it automatically.

From the docs:

A MongoClient object will be the root object. It is thread-safe and is all that is needed to handle connecting to servers, monitoring servers, and performing operations against those servers. [...] It is recommended to store a MongoClient instance in a global place, either as a static variable or in an IoC container with a singleton lifetime. However, multiple MongoClient instances created with the same settings will utilize the same connection pools underneath.

There's a partial/old list of thread-safe MongoDB classes in this SO answer.

like image 191
ashes999 Avatar answered Oct 10 '22 03:10

ashes999