1️⃣ What Is Clean Architecture?
Clean Architecture is a way of organizing code so that:
-
Business rules stay independent of frameworks, UI, and databases.
-
You can change the UI, database, or any external tool without touching core logic.
Think of it as layers arranged like an onion:
-
The most important logic is in the center.
-
Outer layers depend inward, never the other way around.
2️⃣ The Four Main Layers
🟢 1. Entities (Core Domain)
-
What it is: Pure business rules and objects (e.g.,
Order
,Customer
). -
Contains: Properties, methods, validation rules.
-
No external dependencies—not even a database library.
-
Example:
🟡 2. Use Cases / Application Layer
-
Purpose: Coordinates the business rules for specific operations.
-
Contains: Service classes, input/output DTOs, business workflows.
-
Knows about Entities but not about UI or database.
-
Example:
🟠3. Interface Adapters
-
Purpose: Translate data between outer layers (web, DB) and the inner layers.
-
Contains: Controllers, Repository implementations, Mappers, ViewModels.
-
Example:
-
ASP.NET Core Controllers
-
EF Core Repositories
-
🔵 4. Infrastructure
-
Purpose: Actual technical details: database, file system, external APIs, UI.
-
Contains: EF Core DbContext, SMTP email sender, external service clients.
-
This is the most replaceable layer.
3️⃣ Flow of Dependencies
-
Dependency Rule:
Code in the inner circle knows nothing about outer circles. -
Data flows inward → outward, but dependencies only point inward.
4️⃣ How It Looks in .NET Project Structure
A common folder layout:
-
Domain
andApplication
have no reference to Infrastructure or WebAPI. -
Infrastructure
referencesApplication
(to implement interfaces).
5️⃣ Benefits
-
✅ Easy to swap database (SQL → NoSQL)
-
✅ Testable business logic without web server or database
-
✅ Clear separation of concerns
-
✅ Long-term maintainability
6️⃣ Common Patterns Used
-
Dependency Injection: Pass interfaces into constructors.
-
Repository Pattern: Keep data-access code out of core logic.
-
CQRS: Optional, for separating reads and writes.
7️⃣ Example Flow: “Place an Order”
-
Controller (WebAPI) receives HTTP request.
-
Calls Application Layer command handler.
-
Handler manipulates Entities and uses Repository Interface.
-
Infrastructure provides concrete
OrderRepository
using EF Core.
8️⃣ Tips to Implement
-
Start small: separate
Domain
andApplication
first. -
Keep Entities pure—no EF Core attributes directly; use Fluent API or separate configs.
-
Use interfaces for everything external.
Quick Checklist
-
Core domain has zero external references.
-
All dependencies point inward.
-
Business rules testable with plain unit tests.