开发者

Where To Call UnitOfWork.Commit() In A Asp.Net MVC Application

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_EndRe开发者_运维问答quest()?


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜