Dependency Inversion in DDD architecture

178 views Asked by At

I divided my project into 4 layers

  • Show UI layer
  • Service layer processing logic
  • The domain layer connects to the data source
  • Data layer

If the service layer uses classes in the data layer, does it violate the Dependency Inversion principle in SOLID?

3

There are 3 answers

0
Mess On

Yes, Dependency Inversion requires that your high level modules (like your service layer) is not dependent on low level modules (like your data layer). I think in your case, you should use abstraction (interfaces or abstract classes) that the service layer depends on and the data layer implements.

4
plainionist On

The Dependency Inversion Principle says:

High-level modules should not depend on low-level modules. Both should depend on abstractions.

and further

Abstractions should not depend upon details. Details should depend upon abstractions.

This means: the modules/components/DLLs/packages which contain the application logic should not depend on those which contain "technical details". But this would exactly be the case if your service layer depends on your data layer directly (compile dependencies).

To resolve this you need to define abstractions (interfaces or abstract classes) in the high-level module (your service layer) and let the low-level modules implement those. This way the (compile) dependency is "inverted".

For a more detailed explanation of DIP see also: https://youtu.be/-3Z9L6sIAMM

6
R.Abbasi On

First of all, I think your layering should be reconsidered. Especially their names don't reveal their intentions. You can use this convention to name your layers:

  • The data layer is responsible for managing connections and transactions.
  • The domain layer defines the domain models which act as the persisting data models too.

But to be on the same page I use your terminology. If by Data Layer you mean data models, your answer is yes, it won't break DIP.

Does your service layer define repository (or any other) interfaces that your data layer implements? If your answer is yes, it's a wrong answer. The data layer should define the repository interfaces. It defines what should be retrieved and persisted.

Who would implement the repository interfaces? It's going to be your domain layer. It knows how to access the data and how to translate queries and commands.

So the domain layer and the service layer would not depend on each other, they both depend on the abstractions that the data layer defines. The references between layers would be like the below and as a result, no circular dependencies would be created:

service layer => data layer
domain layer => data layer
presentation (UI) layer -> service layer/data layer/domain layer