Service Pattern – Is Unit of Work Valid?

design-patternsserviceunit-of-work

I've been studying design patterns. I've learned about Repositories, Unit Of Work, Dependency Injection, MVC. I'm now learning about Service Layer pattern.

I'm trying to grasp the utility purpose of Unit of Work(if any) in a Service Layer.

From my understanding services provide encapsulation for specific model database access as a main goal. So if I provide an IService to a Controller that controller will only be able to access the specifics provided in a service, whilst if I provide an IUnitOfWork it will have access to all the Repositories available in it.

I mean it seams logical that the IService accesses the Repositories directly since it will encapsulate the database access and provide business logic at the same time.

So in an IService what's the goal of the Unit of Work?
Is it worth having one?

Best Answer

These are two different patterns with completely different purpose:

  • The service layer is about application boundary and API (visibility & granularity of operations);
  • The unit of work is about transaction management and concurrency.

Of course the service layer could group operations that are exposed. For example save a PurchaseOrder together with its dependent LineItems in one operation, instead of an operation for saving PurchaseOrder and another for saving LineItems.

But this grouping / packaging would not solve the question of which item to update in the database if only one LineItem out of 10 in the PurchaseOrder got changed. It doesn't address either the concurrency issues when several users are trying to update the same PurchaseOrder at the same time. And that's the purpose of the unit of work.

The service layer isolates the domain logic from the outside front(e.g. presentation layer). The unit of work is used by the domain logic back-office.