repository-patternunit-of-workrepository-design

Repository & Unit of Work Design Pattern


This may be more about personal preference than anything but I have been trying to wrap my head around using the Repository and Unit of Work pattern yet I have seen to very different uses and would like to know which is 'better' and why.

Use 1:
In this use, the Repository is put into the Unit of Work

Use 2:
In this use, the Unit of Work is put into the Repository


Solution

  • It's .... complicated. First start with my simple explanation of what a Repository is. Next, the UoW concept is overused and abused. Considering repositories, the DDD approach of working with Aggregates means the repository encapsulates a UoW as everything in the aggregate root must be persisted as a whole. At the db level, UoW simply means use transactions and this works even with multiple repositories if they use the same transaction.

    However, most of the time this is the wrong design, because it usually works only for non-distributed apps and requires some ACID compliant storage. While it might be your case, the fact that you're using the Repository pattern means you want your app to be persistence ignorant and this means your app shouldn't know about a UoW which is a pattern usable inside persistence (by an ORM or directly via a db transaction).

    So, I'd say that the 'correct' answer is: a repository might use a UoW implementation, depending on the particular needs. If you're using an ORM, then the UoW is used automatically.