在 Asp.Net MVC 应用程序中调用 UnitOfWork.Commit() 的位置
我应该在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的控制器应如下所示:
unitOfWork 应在控制器级别声明为:
并注入到控制器的构造函数中 - 最好在每个 HTTP 请求中使用 DI。
当您考虑一下时,Web 应用程序上下文中的工作单元通常是 HTTP 请求。
HTTP 请求仅定向到一个操作方法来执行工作。当然,您有 PRG 模式(随后重定向到 HttpGet 操作) - 但每个 HTTP 请求应该只有 1 个
[HttpPost]
操作调用。因此,在操作方法级别提交 UoW 是有意义的。
您应该有两个 IUnitOfWork 实现:
因此,在单元测试时 - 只需注入 InMemoryUnitOfWork (例如,将更改提交到静态
List
中)Your controller should look something like this:
unitOfWork should be declared at the controller-level as:
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:
So when unit testing - just inject InMemoryUnitOfWork (which commits changes into a static
List<T>
, for example)听起来您的 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.