domain driven design repository

Viewed 639

I am learning DDD topic from scratch and on many DDD examples I see "repository interface" sitting in domain. What is real purpose of this repository actually/what does it do or solve exactly? Does this correspond or have some connection to persistence layer implementation?

Thank you.

2 Answers

What is real purpose of this repository actually/what does it do or solve exactly?

The reference for the REPOSITORY pattern in the context of domain-driven-design is chapter 6 of the "blue book" by Eric Evans. That is the chapter where he discusses lifecycle management patterns.

The repository is a facade, intended to support the illusion that DOMAIN ENTITIES (a chapter 5 pattern) are kept in an in-memory collection, somewhere. So when your process needs an entity, it asks the repository for it (usually offering an identifier as a hint).

It's a form of information hiding, in the Parnas 1971 sense; we can freely switch between transient collections stored in memory and durable collections stored on disk, or in the RDBMS, or in the key/value store. Only the implementation(s) of the repository need to worry about the specifics of the plumbing.

The motivation was largely to separate developer focus; the separation of ideas permits developers working on the "business rules" to concentrate on the domain, without being distracted by the concerns of storage and retrieval.

The Repository interface sits in the Domain layer and the Repository itself is implemented in the Infrastructure layer. Defining the Repository interface in the Domain layer allows to easily switch between Infrastructure implementations, knowing that all follow the same interface.

Ultimately, the Application layer will call a Repository implementation from the infrastructure layer. To go further, you can even define an Application interface based on the Repository interface, and then an Application implementation where you inject the selected Repository implementation from the Infrastructure layer.

Related