Question

Who has the responsability


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

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top