Combining Clean Architecture in both ASP.
NET Core MVC and Web API using Dapper involves
creating a structured, decoupled, and maintainable solution that follows Clean Architecture
principles. Clean Architecture aims to separate concerns into distinct layers, enabling easy
testability and flexibility.
Key Layers of Clean Architecture
1. Domain Layer (Core):
o This layer contains Entities, Value Objects, and Interfaces.
o It is independent of any infrastructure or external concerns.
o Business rules and logic live here.
2. Application Layer (Use Cases):
o Contains Use Cases, DTOs, and Service Interfaces.
o Coordinates the flow of data between the Domain and the outside world.
o Use Cases call the domain layer to implement business logic.
3. Infrastructure Layer (Dapper, Data Access):
o Implements external concerns like database access, APIs, etc.
o Dapper will be placed here to handle data persistence.
4. Presentation Layer (MVC & Web API):
o Handles UI and web-related logic. This includes Controllers in MVC and Web API.
o This layer consumes the application layer via Dependency Injection to access
business logic.
Example: Clean Architecture Setup with Dapper in MVC and Web API
Step-by-Step Implementation
1. Project Structure
o Domain Layer (Class Library):
▪ Entities/: Define business objects like Customer, Order.
▪ Interfaces/: Define repository and service interfaces (e.g.,
ICustomerRepository).
o Application Layer (Class Library):
▪ Services/: Use cases such as CreateOrderService, GetCustomerDetails.
▪ DTOs/: Define data transfer objects for UI or API consumption.
▪ Interfaces/: Interfaces for services that coordinate between layers.
o Infrastructure Layer (Class Library):
▪ Repositories/: Implementation of ICustomerRepository using Dapper for
data access.
▪ Dapper SQL queries and data mapping to entities reside here.
o Presentation Layer (MVC and Web API):
▪ MVC Controllers (for UI interaction) and API Controllers (for Web API
interaction).
▪ These controllers communicate with services in the Application Layer via
Dependency Injection.
Example Code
Domain Layer