There are a lot of posts discussing repository implementations, unit of work and ASP.NET MVC. This post is an attempt to give you and answer which addresses all three issues.
Do NOT create generic repositories. They look fine when you look at them. But as the application grow you’ll notice that you have to do some workarounds in them which will break open/closed principle.
It’s much better to create repositories that are specific for an entity and it’s aggregate since it’s much easier to show intent. And you’ll also only create methods that you really need, YAGNI.
Generic repositories also removes the whole idea with choosing an OR/M since you can’t use your favorite OR/Ms features.
Unit Of Work
Most OR/Ms available do already implement the UoW pattern. You simply just need to create an interface and make and adapter (google Adapter pattern) implementation for your OR/M.
public interface IUnitOfWork : IDisposable
NHibernate sample implemenetation:
public class NHibernateUnitOfWork : IUnitOfWork
private readonly ITransaction _transaction;
public NHibernateUnitOfWork(ISession session)
if (session == null) throw new ArgumentNullException("session");
_transaction = session.BeginTransaction();
public void Dispose()
public void SaveChanges()
I prefer to use an attribute to handle transactions in MVC. It makes the action methods cleaner:
public ActionResult Update(YourModel model)
And the attribute implementation:
public class TransactionalAttribute : ActionFilterAttribute
private IUnitOfWork _unitOfWork;
public override void OnActionExecuting(ActionExecutingContext filterContext)
_unitOfWork = DependencyResolver.Current.GetService<IUnitOfWork>();
public override void OnActionExecuted(ActionExecutedContext filterContext)
if (filterContext.Exception == null)