在 Asp.Net MVC 应用程序中调用 UnitOfWork.Commit() 的位置

发布于 2024-10-08 04:37:40 字数 211 浏览 8 评论 0原文

我应该在 Asp.Net MVC 应用程序中的何处调用 UnitOfWork 上的 Commit() ?并且仍然保持我的控制器可进行单元测试。

我使用 HttpModule 吗?创建一个基本控制器并使用OnActionExecuted?或者Global.asax:Application_EndRequest()

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

策马西风 2024-10-15 04:37:40

您的控制器应如下所示:

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

   return View();
}

unitOfWork 应在控制器级别声明为:

IUnitOfWork unitOfWork;

并注入到控制器的构造函数中 - 最好在每个 HTTP 请求中使用 DI。

当您考虑一下时,Web 应用程序上下文中的工作单元通常是 HTTP 请求。

HTTP 请求仅定向到一个操作方法来执行工作。当然,您有 PRG 模式(随后重定向到 HttpGet 操作) - 但每个 HTTP 请求应该只有 1 个 [HttpPost] 操作调用。

因此,在操作方法级别提交 UoW 是有意义的。

您应该有两个 IUnitOfWork 实现:

  • EntityFrameworkUnitOfWork : IUnitOfWork
  • InMemoryUnitOfWork : IUnitOfWork

因此,在单元测试时 - 只需注入 InMemoryUnitOfWork (例如,将更改提交到静态 List 中)

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)

淑女气质 2024-10-15 04:37:40

听起来您的 UI 应该将 commit 调用发送到域控制器,然后域控制器应该将该调用传递给域层中的相关方。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文