Take the 2-minute tour ×

Where should I call Commit() on my UnitOfWork in a Asp.Net MVC app? And still keep my controllers unit testable.

Do I use a HttpModule? Create a base controller and use OnActionExecuted? Or Global.asax: Application_EndRequest()?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

Your controller should look something like this:

public ActionResult SubmitOrder(Order o)
   catch (YourCustomExceptionClass exc) 

   return View();

unitOfWork should be declared at the controller-level as:

IUnitOfWork unitOfWork;

And injected into the ctor of the controller - preferably with DI per HTTP Request.

When you think about it - a unit of work in the context of a web application is usually a HTTP Request.

And a HTTP request is directed to only one action method to perform the work. Of course you have the PRG pattern (redirect to a HttpGet action afterwards) - but there should be only 1 [HttpPost] action call per HTTP request.

Therefore it makes sense to commit the UoW at the action method level.

You should have two implementations of IUnitOfWork:

  • EntityFrameworkUnitOfWork : IUnitOfWork
  • InMemoryUnitOfWork : IUnitOfWork

So when unit testing - just inject InMemoryUnitOfWork (which commits changes into a static List<T>, for example)

share|improve this answer

It sounds like your UI should send the commit call to the domain controller which should then pass the call onto the relevant parties in the domain layer.

share|improve this answer

Your Answer


