How to ensure disposal of MongoDB connection (DB Hanging)
First some context: I have an MVC3 .net project which, for the sake of brevity, is set up something like the following:
开发者_JAVA技巧Controller - Instantiates a service object (described below) - Uses service to retrieve db record from mongo (e.g. _service.GetPerson(id)) - Passes domain to view
Service - Instantiates MongoRepository (described below) - Calls method to retrieve db record (e.g. _mongoRepository.Single(c => c.Id == id))
MongoRepository : IDisposable - Constructor (_server = Mongo.Create(ConfigurationManager.ConnectionStrings["mongodb"].ConnectionString)) - Single method (below) - Dispose method
public T Single<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression) where T : class, new()
{
return _server.GetCollection<T>().AsQueryable()
.Where(expression).SingleOrDefault();
}
Now, this is my question, as you can see MongoRepository implements the IDisposable interface, and I believe the best way to ensure Dispose is called is with the 'using' block, but
1) when/where should that be? Should it be in the Service layer, inside the method calling the mongoRepository.Single method?
2) when should the MongoRepository be instantiated?
If more code is necessary to answer please let me know, I was trying to keep it short. Thanks in advance.
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?
精彩评论