I am writing an ASP.Net MVC 3 Web Application using Entity Framework 4.1. My Unit of Work class is the same as described in this excellent tutorial http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
However, instead of injecting my UoW class into my Controller, I do so in my Service Class, like so
public class ListService : IListService
{
private IUnitOfWork _uow;
public ListService(IUnitOfWork uow)
{
_uow = uow;
}
public IList<List> GetAllListTypes()
{
return _uow.Lists.Get().OrderBy(l => l.description).ToList();
}
}
My Unit of Work class is like this
public class UnitOfWork : IUnitOfWork, IDisposable
{
readonly LocumEntities _context = new LocumEntities();
private GenericRepository<List> _lists = null;
public IGenericRepository<List> Lists
{
get
{
if (_lists == null)
{
_lists = new GenericRepository<List>(_context);
}
return _lists;
}
}
public void Commit()
{
_context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
And this all works fine. However, you'll notice I have methods in my UoW class to dispose of the DbContext. I wish to dispose of the UoW class after every business transaction like is done in the above mentioned tutorial, they do this by using the following code in their controller
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
I tried to amend this method and place it in my service class however it does not work, ie, the dispose method in the UoW class never gets called
protected override void Dispose(bool disposing)
{
_uow.Dispose();
}
I would greatly appreciate if someone could point me in the correct direction with how to dispose of my UoW class.
Thank you.