Design Patterns - Repository Pattern

The repository pattern is a design pattern to encapsulate the methods to access to a data source and access to them from any layer using Inversion of Control (IoC).

It provides better maintainability, testability, security, and decoupling from the persistence method.

Characteristics

  • The repository methods receives (as parameters) and returns Domain layer objects such as Aggregate Roots, Entities or Value Objects.
  • The query methods such as get or find are asynchronous and return promises, which means that the database is instantly queried.
  • The data manipulation commands such as add, update or delete are not asynchronous, because these commands are not going to be applied in the database automatically, but rather they are accumulate in the same transaction, and then they are applied using the Unit of Work pattern.

The repository pattern can be splitted into:

Generic repository

  • The interface of the generic repository is stored in the Domain layer.
  • Generic repositories should not be implemented, but the specialized repositories, unless it is implemented in an abstract class.
  • It is not mandatory to have a generic repository as long you use the specialized ones.

Specialized repository

  • The interfaces of the specialized repositories are stored in the Domain layer.
  • The implementations of the specialized repositories are stored in the Infrastructure layer and you can use a database driver or an ORM.
  • Can extend from the generic repository.
  • Each Aggregate has at least one specialized repository.

Examples