SDReyes
SDReyes

Reputation: 9954

How to implement Unit of work in MVC: Responsibility

Who has the responsability


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

Upvotes: 7

Views: 2137

Answers (4)

Spydermary
Spydermary

Reputation: 31

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.

Upvotes: 3

JoseMarmolejos
JoseMarmolejos

Reputation: 1770

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.

Upvotes: 2

zihotki
zihotki

Reputation: 5191

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.

Upvotes: 10

Mark Dickinson
Mark Dickinson

Reputation: 6633

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.

Upvotes: 5

Related Questions