First some context: I have an MVC3 .net project which, for the sake of brevity, is set up something like the following:
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.