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

3

17

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.

Pash answered 21/9, 2015 at 19:25 Comment(1)
There appears to be a bug in the current version of the driver (2.11), once I create a new MongoClient in a simple console application, the console program wont close on its own.Tweed
O
27

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.

Oakleil answered 21/9, 2015 at 20:3 Comment(1)
This is how I am handling my IMongoClient, it is in a singleton logging class that all of my application can access. I guess this answer also basically convinces me that it needs nothing special to close it. // Though I am still partially unsure if I should keep the Mongo daemon running after the application is closed.Pash
U
1

The question seems to have been already kinda asked here at When should i be opening and closing MongoDB connections?

If it's accepted answer,

I would leave the connection open as re-creating the connection is costly. Mongo is fine with lots of connections, open for a long time. What you ideally should do is to share the connection with all parts of your application as a persistent connection. The C# driver should be clever enough to do this itself, so that it does not create too many connections, as internally it uses "connection pooling" that makes it even re-use connections. The docs say: "The connections to the server are handled automatically behind the scenes (a connection pool is used to increase efficiency)."

works fine for you then all well and good. Even the MongoDB C# driver's quick tour page lends the same advice -

Typically you only create one MongoClient instance for a given cluster and use it across your application. Creating multiple MongoClients will, however, still share the same pool of connections if and only if the connection strings are identical.


Otherwise, I think you can simply put your call to create the connection in a using(){} code block. It automatically calls the dispose method for you (as it implements the IDisposable pattern). You should use this block for any resource you want disposed.

Umbilication answered 21/9, 2015 at 20:1 Comment(2)
I had seen that answer but it was more geared toward having multiple IMongoClients versus how to shut them down properly. I think ashes999 answered it mostly below. // Though I am still partially unsure if I should keep the Mongo daemon running after the application is closed.Pash
@KDecker: I can't see any difference between the other answer and mine. Anyway, even if you close the connection there will be no effect from MongoDB's perspective as the connection is pooled. You can close it for your peace of mind.Umbilication
P
1

From my experience, the correct way is as answered, but even following these recommendations, I still was having random EndOfStreamException. It seems that some problems are caused by the internet provider closing the connection after some time.

I Solved it by adding:

MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
            settings.SslSettings = new SslSettings() { EnabledSslProtocols = SslProtocols.Tls12 };
            settings.MaxConnectionIdleTime = TimeSpan.FromSeconds(30);
Pearliepearline answered 17/6, 2017 at 15:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.