Domain-Driven Design & Clean Architecture

The Clean Architecture is a set of rules and principles for organizing a code development project, and how all its components interact with each other.

The Clean architecture can be applied in the Domain-Driven Design because both focus on separating the domain code from the external code.

There are some Clean Architecture models, such as:

  • N-Tier Architecture.
  • Hexagonal Architecture (Ports and Adapters).
  • Onion Architecture.

Each of these models has its details that differentiate them from the others, but they also have details in common, such as the organization by layers:

The Clean Architecture layers can be represented by forming concentric circles:

Clean Architecture layers

Those layers follow the Dependency Rule, which says that inner circles do not know anything about the outer circles, so if any inner layer requires to use of an outer layer, it would use Inversion of Control (IoC).

Clean Architecture layers

Domain layer

  • This layer is located at the center (Core).
  • Following the Dependency Rule: This layer doesn’t know about the Application layer nor the Infrastructure layer.
  • Is not recommended that this layer use external packages, such as any NuGets, NPM, etc.
  • Is not recommended that this layer have dependencies on other projects.
  • This layer contains:

Application layer

  • Following the Dependency Rule: This layer knows about the Domain layer but not about the Infrastructure layer.
  • This layer contains:
    • Domain Event Handlers.
    • Use Cases.
    • The contract of external services, such as a service to send emails.

Infrastructure layer

  • Following the Dependency Rule: This layer knows about the Domain layer and the Application layer.
  • This layer contains:
    • The implementation of the repositories.
    • The implementation of external services declared in the Application layer.
    • Object-Relational Mapping (ORM) of the database.
    • The files of the API framework (Controllers, Middlewares, etc.).