如何在 MVC 中实现工作单元:职责
谁有责任
谁有责任启动和完成 MVC 架构中的工作单元?
Who has the responsability
Who has the responsibility to start and finish the Unit of work in a MVC architecture?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这不是控制者的责任,它违反了SRP。控制器根本不应该知道 UoW。在 Web 中,通常对服务器的每个请求使用一个 UoW。在这种情况下,UoW 应在请求结束时进行处理,并在请求开始后的某个位置启动(理想情况下,UoW 的启动应该是惰性的)。执行此操作的最佳位置是使用 Application_EndRequest 和 Application_BeginRequest 处理程序的 Global.asax(或您的 HttpApplication 类)。
这可以通过 IOC 框架轻松实现(我最喜欢的是 Windsor),请参阅这个问题< /a> 了解实施细节。
It's not a responsibility of a controller, it violates SRP. Controller should not even know about UoW at all. In web, one UoW per request to server is usually used. In this case UoW should be disposed at the end of a request and started somewhere after the beginning of a request (ideally start of a UoW should be lazy). The best place to do this is Global.asax (or your HttpApplication class) using Application_EndRequest and Application_BeginRequest handlers.
This can be easily achieved with an IOC framework (my favorite is Windsor), see this question for implementation details.
控制器。这将获取上下文,以便您可以开始和完成工作单元。例如,每个请求的 nHibernate 会话需要您知道请求何时开始和完成,因此您需要上下文来为您提供请求。
The controller. This gets the context, so you can start and finish the unit of work. For example a nHibernate session per request would need you to know when the request had started and finished, so you need the context to give you the request.
我是松散耦合架构的信徒。我的控制器对存储库、上下文或工作单元一无所知。我创建了控制器调用的服务层(不确定这是正确的术语)。然后,该服务与存储库 (dll) 一起保存所有数据。
I am a believer in loosely coupled architecture. My controller knows NOTHING about the repository, context or unitofwork. I have created a service layer (not sure that is the right term) that the controller calls. This service then works with the repository (dll) to persist all data.
正如 zihotki 所说,如果您将此责任交给控制者,您将违反 SRP。这是一种面向数据操作的模式,因此控制器不应该担心……这将导致两种违规:一种违反 SRP,另一种违反 SoC 原理。
至于谁有责任,这是由您的架构定义的。 StartRequest/EndRequest 建议似乎足够可靠。
As zihotki said you would be violating the SRP if you give this responsibility to the controller. This is a data manipulation oriented pattern, and as such should not be a concern for the controller ... that would make it two violations: one for the SRP and anothrt for the SoC principle.
As for who has the responsibility, that's something to be defined by your architecture. The StartRequest/EndRequest suggestion seems solid enough.