I have a important question for implementation about Domain Driven Design. On the representation of layer architecture in evans's book, the Domain to references the layer Infrastructure this being the lowest layer, however I see in all implementations on the Internet the contrary, the infrastructure layer referencing the domain layer, maybe because of the implementation of the repository pattern using an ORM. What you guys think about this? Someone would have an example that implentasse exactly as Evans's book.
2 Answers
The examples that you see where interfaces lives in the domain (e.g. UserRepository
) and their implementation lives in the infrastructure (e.g. HibernateUserRepository
) are applying the Dependency Inversion Principle (DIP) to the traditional Layered Architecture.
In the traditional Layered Architecture, high level modules should depend on low-level modules. If we look at the standard layers order, we would have Domain -> Infrastructure
.
Do we really want our domain to depend on infrastructure details? By applying the DIP principle, we inverse the dependency and make Infrastructure depend on the Domain layer, however it doesn't depend on concretions, but on abstractions.
Here's what the DIP principle states:
A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend on details. Details should depend on abstractions.
Source: http://en.wikipedia.org/wiki/Dependency_inversion_principle
Are you sure you are looking at dependencies correctly? Repositories are not exactly infrastructure, they are located in between your domain and your data access layer.
As stated in Fowler's book, repository
Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.
If you are using a database, or, as you noted, an ORM, your repositories implementation will reference the ORM. Quite often, repository is implemented as a generic class, the only way it then "references" the domain as such is as it uses the base "entity" class for the generic constraint.
Very often data retrieval queries "by this" and "by that" are implemented in repository classes but this is not a very good practice. This work is for queries, or specifications, that a repository should be able to execute without knowing much of the details about them.