Question

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()?

Was it helpful?

Solution

Your controller should look something like this:

[HttpPost]
public ActionResult SubmitOrder(Order o)
{
   try
   {
       repository.Add(o);
       unitOfWork.Commit();
   }
   catch (YourCustomExceptionClass exc) 
   {
      ModelState.AddError(exc.ToString());
   }

   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)

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top