Question

Which layer should the repository classes go in? Domain or Infrastructure?

Was it helpful?

Solution

I guess that depends how You are going to rely on them.

Question is - are You going to allow Yourself to use repositories from inside of domain?
If so - then You are forced to put them in.

I myself like to put them outside of domain. So - typical life cycle of something looks like this =>

UI => Controller => retrieve aggregate root from repo => call logic through aggregate root => if new aggregate root created, add it to repo.

Sometimes controller calls application service that does some additional stuff besides just retrieving root and calling function on it. But idea is same - domain knows nothing about persistence.


While (as I see it) there's nothing wrong with putting repos in domain (or at least abstractions of them), it makes Your domain more aware of persistence. Sometimes that can solve problems, but generally - that will definitely make Your domain more complex.

Use what seems more natural for You and be ready to switch Your ways any time.

OTHER TIPS

The repository interfaces are part of the domain. The actual implementation of the interfaces should be part of the infrastructure.

Repository implementation classes, together with separate interfaces (if they exist) should go into the domain layer.

The reason is given by the fundamental rule to be followed in a layered architecture: a lower layer must not depend on a higher layer.

If we accept this rule (otherwise it's not a layered architecture), then putting repository implementations into the infrastructure layer would make it dependant on the domain layer, therefore violating the fundamental rule of layering.

For example, when we create a new domain entity, we put it in the domain layer; and since a repository (both its interface and its implementation) must inevitably depend on the domain entity, it means the repository must also go into the domain layer. Otherwise, we would be changing the infrastructure layer whenever a domain entity was added/removed/modified in the domain layer.

Other concerns, such as keeping the domain layer "clean" and independent of persistence details, can and should be achieved by using the appropriate infrastructure services from the implementations inside the domain layer. For example, in Java we can use JPA to implement repositories with very little code, and no SQL/JDBC or database-specific code (whether it's really a good idea to implement repositories with JPA is another discussion; in any case, JPA entities will make use of JPA annotations anyway).

References: Wikipedia, MSDN

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top