Clean Architecture


What is Clean Architecture?

Clean Architecture = Architecture pattern that separates concerns into layers with clear dependency rules

Created by: Robert C. Martin (Uncle Bob)

Key Principles:

  • Independence - Framework, UI, database independent

  • Testability - Business logic easily testable

  • Maintainability - Easy to change and extend

  • Separation of Concerns - Each layer has specific responsibility

  • Dependency Rule - Dependencies point inward only

The Dependency Rule

CRITICAL: Source code dependencies can only point INWARD

┌─────────────────────────────────────┐
│     External (UI, Database, etc)    │  ← Outer Layer
├─────────────────────────────────────┤
│     Infrastructure & Frameworks     │
├─────────────────────────────────────┤
│     Application (Use Cases)         │
├─────────────────────────────────────┤
│     Domain (Entities, Business)     │  ← Inner Layer (Core)
└─────────────────────────────────────┘

Dependencies flow: Outer → Inner (never Inner → Outer)

The Four Layers

1. Domain Layer (Core / Entities)

Location: Center of architecture Dependencies: None (completely independent) Contains:

  • Entities (business objects)

  • Value Objects

  • Domain Events

  • Enums

  • Exceptions

  • Interfaces (repository contracts)

Rules:

  • ❌ No dependencies on other layers

  • ❌ No framework dependencies

  • ❌ No database concerns

  • ✅ Pure business logic only

2. Application Layer (Use Cases)

Location: Second layer from center Dependencies: Domain layer only Contains:

  • Use Cases / Application Services

  • DTOs (Data Transfer Objects)

  • Mapping Profiles

  • Validators

  • Interfaces for infrastructure

Rules:

  • ✅ Can depend on Domain

  • ❌ Cannot depend on Infrastructure or Presentation

  • ✅ Orchestrates business logic

  • ✅ Defines interfaces for external services

3. Infrastructure Layer

Location: Third layer Dependencies: Domain and Application layers Contains:

  • Repository implementations

  • Database context (EF Core)

  • External service implementations

  • File system access

  • API clients

Rules:

  • ✅ Can depend on Domain and Application

  • ✅ Implements interfaces from Domain/Application

  • ❌ Should not contain business logic

4. Presentation Layer (UI / API)

Location: Outermost layer Dependencies: Application and Infrastructure (for DI setup) Contains:

  • Controllers (API)

  • Views (MVC)

  • ViewModels

  • API models

  • Startup/Program.cs

Rules:

  • ✅ Can depend on Application

  • ✅ Configures DI container

  • ❌ Should not contain business logic

  • ❌ Should not directly access Domain


Project Structure


CQRS Pattern in Clean Architecture

CQRS = Command Query Responsibility Segregation

Concept: Separate read operations from write operations

Commands (Write Operations)

Queries (Read Operations)

Controller with CQRS


MediatR Integration

MediatR = Library for implementing CQRS and Mediator pattern

Commands with MediatR

Queries with MediatR

Controller with MediatR


Validation with FluentValidation

Validator

MediatR Pipeline Behavior for Validation


Repository Pattern

Generic Repository


Unit of Work Pattern


Exception Handling

Domain Exceptions

Global Exception Middleware


Testing Strategy

Domain Tests

Application Tests


Best Practices

1. Keep Domain Logic Pure

2. Use Value Objects

3. Separate Read and Write Models

4. Use DTOs for API Boundaries

5. Dependency Injection Configuration


Quick Reference: Clean Architecture Rules

✅ DO

  1. Domain Layer:

    • Keep pure business logic

    • No external dependencies

    • Define repository interfaces

    • Throw domain exceptions

  2. Application Layer:

    • Orchestrate use cases

    • Define DTOs

    • Define service interfaces

    • Validate input

  3. Infrastructure Layer:

    • Implement repositories

    • Implement external services

    • Database concerns

    • File system access

  4. Presentation Layer:

    • Handle HTTP concerns

    • Map DTOs to API models

    • Configure DI container

    • Minimal logic

❌ DON'T

  1. Domain Layer:

    • Don't reference other layers

    • Don't use EF Core DbContext

    • Don't access database directly

    • Don't use framework types

  2. Application Layer:

    • Don't access database directly

    • Don't contain presentation logic

    • Don't implement infrastructure

  3. Infrastructure Layer:

    • Don't contain business logic

    • Don't expose EF entities to application

  4. Presentation Layer:

    • Don't contain business logic

    • Don't access database directly

    • Don't depend on infrastructure (except DI)


Dependency Flow Diagram


Guide Complete! This comprehensive Clean Architecture guide covers all layers, dependency rules, CQRS, MediatR integration, validation, repository patterns, and best practices for building maintainable .NET applications! 🏗️

Last updated