Clean Architecture for .NET WebAPIs simplifies code maintainability and scalability for enterprise scale-apps. It separates the implementation into four layers, each in its own .NET project: API (Presentation), Application, Infrastructure, and Domain.
API Layer:
- Handles routes and controllers.
Application Layer:
- Manages core business logic using services from the Infrastructure layer.
Infrastructure Layer:
- Connections to databases and external services.
Domain Layer:
- Holds Entities and Classes shared by the Application and Infrastructure layers.
How do layers communicate with each other?
The API layer's controllers communicate with Command/Query Handlers through MediatR, implementing the CQRS pattern. The Application layer handles core business logic by calling services from Infrastructure layer.
The Application layer is not dependent on Infrastructure layer, meaning it cannot directly call service from the infrastructure layer. To bridge this gap, we create interfaces in the Application layer. These interfaces are then fulfilled by actual objects injected from service classes using dependency injection.
The goal of inverting control between the Application and Infrastructure layers is to decouple service implementations from the core logic. This makes the architecture more adaptable to changes in databases or services while keeping the business logic stable. The Domain layer acts as a shared space for entities used by both the Application and Infrastructure layers.
More on Clean Architecture? Watch Jason Taylor's video here