I'm currently working on a web app which consist of 6 layers:
- Web (reference to ViewModels and Controllers)
- ViewModels
- Controllers
- Services (reference to Data and Entities)
- Data (reference to Entities)
- Entities
What I'm trying to is to implement a "UnitOfWork" pattern, and therefore I have a class thats injected by DI for that job which makes it possible to do .commit() in the actionresult in the controller when I'm done with the database.
Now is my question... Where should this UnitOfWork class be placed? It's at the moment in my Data layer but that requires the Controller layer to reference the Data layer AND the Service layer, which is odd in my opinion... Should I move the UnitOfWork class/interface to the Service layer and use DI?
Unless you're using the Repository pattern in your Data layer, you're wasting your time.
The point of a UoW is to handle changes across multiple Repository instances, this is done in the following ways:
The Unit of Work do two things:
Commit()
methodIt's a little tricky to get it all setup, but once you do, the flow should be like this:
Essentially, each layer takes an instance of the "next layer" in their constructor. Everything should be DI'ed and interface-driven. The UoW has not reliance on anything - but the Repository relies on it for persistence to the "internal memory" (ORM), then the UoW "Commit" will push the changes out to the database (basically wraps the "SaveChanges" method).
As the Unit of Work is an infrastructure/persistence/database/transactional concern, it should go into your Data layer. Should only be referenced by Controllers.