How to ensure disposal of MongoDB connection (DB Hanging) How to ensure disposal of MongoDB connection (DB Hanging) mongodb mongodb

How to ensure disposal of MongoDB connection (DB Hanging)


1) It sounds like you are instantiating and using the Repository in the Service class. So instead of

var _mongoRepository = new MongoRepository(..);_mongoRepository.Single(...);

you would have

using (var _mongoRepository = new MongoRepository(..)){    _mongoRepository.Single(..);}

If you are wrapping Mongo calls in the MongoRepository class then make sure that the Dispose method properly cleans up the _server connection (close/disconnect/whatever). It looks like you are creating the connection in the constructor, using it in the method but never closing it.

2) From my experience it is preferable to open a DB connection as late as possible and close it as early as possible - rather than opening it and using it several times for different queries.

There's a good discussion on MongoDB (C#) connections at .NET best practices for MongoDB connections?