How to implement Unit of work in MVC: Responsibility

前端 未结 4 1602
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 09:08

Who has the responsability


Who has the responsibility to start and finish the Unit of work in a MVC architecture?

相关标签:
4条回答
  • 2021-01-12 09:37

    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.

    0 讨论(0)
  • 2021-01-12 09:40

    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.

    0 讨论(0)
  • 2021-01-12 09:45

    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.

    0 讨论(0)
  • 2021-01-12 09:48

    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.

    0 讨论(0)
提交回复
热议问题