A comprehensive implementation of Clean Architecture combined with Domain-Driven Design (DDD) using .NET 8. This v1.0.0 release showcases a production-ready Modular Monolith architecture with Custom CQRS Dispatcher, Central Package Management, and DbMigrator tooling for enterprise applications.
- Overview
- Architecture
- Project Structure
- Technologies
- Features
- Getting Started
- Development Guide
- Testing
- Contributing
This project is a comprehensive implementation of Clean Architecture combined with Domain-Driven Design (DDD) using .NET 8.
v1.0.0 represents a production-ready foundation featuring:
- Modular Monolith Architecture - 3 business modules (Identity, Catalog, Auditing) with isolated schemas
- Custom CQRS Dispatcher - Unique implementation replacing MediatR with automatic validation and performance monitoring
- DbMigrator Tool - Production-ready database migration orchestrator for CI/CD pipelines
- Central Package Management - Unified dependency versioning across 18 projects
- 19 Working API Endpoints - Fully functional REST APIs with Swagger documentation
The implementation showcases enterprise architecture principles with patterns like CQRS, Repository Pattern, Unit of Work, Specification Pattern, Domain Events, and Modular Monolith design.
๐ Current Status (February 2026) - v1.0.0 Released:
- โ Custom CQRS Dispatcher: Complete replacement of MediatR - automatic validation, performance monitoring, structured logging with emojis (๐โก๐ข)
- โ DbMigrator Tool: Multi-DbContext orchestration, health checks, idempotent execution, Serilog logging
- โ Central Package Management: Directory.Packages.props managing all 18 projects
- โ 3 Business Modules: Identity (8 endpoints), Catalog (11 endpoints), Auditing (1 endpoint)
- โ BuildingBlocks: 5 shared projects providing domain base classes, CQRS infrastructure, API components
- ๐ Completion: ~75% - Production foundation complete, testing infrastructure and advanced auth workflows planned for v1.1.0
- ๐๏ธ Clean Architecture: Clear separation of layers and dependencies with modular monolith structure
- ๐ฏ Custom Dispatcher: Unique CQRS implementation with built-in validation, logging, and performance monitoring (replaces MediatR)
- ๐ CQRS Pattern: Complete Command Query Responsibility Segregation with automatic handler registration
- ๐๏ธ DbMigrator: Professional database migration tool orchestrating multiple DbContexts with health checks
- ๐ฆ Central Package Management: Unified dependency versioning via Directory.Packages.props
- ๐ฏ Domain-Driven Design: Focus on business logic and domain model
- ๏ฟฝ Repository & Unit of Work: Enterprise-grade data access patterns with Specification Pattern
- ๐ 19 Working API Endpoints: Identity (8), Catalog (11), Auditing (1)
- ๐ Security Foundation: JWT authentication infrastructure, CORS configuration
- ๐ Interactive Swagger UI: Comprehensive API documentation with live testing
- ๐ Production Tooling: DbMigrator for CI/CD, structured logging with Serilog
This repository demonstrates Clean Architecture principles by Uncle Bob implemented across different architectural patterns. Currently, it includes:
A complete monolithic application following Clean Architecture with 4 main layers:
- Entities: Core business objects
- Value Objects: Immutable objects
- Domain Events: Business events
- Repository Interfaces: Data access contracts
- Domain Services: Business logic services
- Use Cases: Application business rules
- Commands & Queries: CQRS implementation
- Handlers: Command/Query handlers
- DTOs: Data transfer objects
- Validators: Input validation
- Mappers: Object mapping
- Persistence: Entity Framework Core implementation
- External Services: Third-party integrations
- Caching: In-memory and distributed caching
- Logging: Structured logging with Serilog
- Authentication: Identity management
- Configuration: Application settings
- Web API: RESTful APIs with ASP.NET Core
- Controllers: API endpoints
- Middleware: Request/Response pipeline
- API Documentation: Swagger/OpenAPI integration
- Microservices Architecture - Distributed services with API Gateway (Partially Implemented)
- Event-Driven Architecture - Message-driven communication (Planned)
- CQRS with Event Sourcing - Advanced CQRS implementation (Planned)
- Serverless Architecture - Cloud-native serverless approach (Planned)
CleanArchitecture/
โโโ src/
โ โโโ BuildingBlocks/ # ๐งฑ Shared Building Blocks
โ โ โโโ BuildingBlocks.Domain/ # Base entities, domain events
โ โ โ โโโ Entities/ # Entity.cs, IHasKey, ITrackable
โ โ โ โโโ Events/ # IDomainEvent
โ โ โ โโโ Repositories/ # IRepository, IUnitOfWork
โ โ โ โโโ Specifications/ # Specification Pattern
โ โ โ
โ โ โโโ BuildingBlocks.Application/ # ๐ฏ Custom Dispatcher & CQRS
โ โ โ โโโ CQRS/ # ICommand, IQuery, ICommandHandler, IQueryHandler
โ โ โ โโโ Dispatcher/ # โญ Custom Dispatcher (v1.0)
โ โ โ โ โโโ IDispatcher.cs # Main dispatcher interface
โ โ โ โ โโโ Dispatcher.cs # Implementation with validation
โ โ โ โ โโโ IDomainEventHandler.cs # Domain event handler
โ โ โ โโโ DTOs/ # BaseDto
โ โ โ โโโ Results/ # Result pattern
โ โ โ โโโ Validation/ # IValidator interface
โ โ โ
โ โ โโโ BuildingBlocks.Infrastructure/ # Common infrastructure
โ โ โ โโโ Persistence/ # Base repositories
โ โ โ
โ โ โโโ BuildingBlocks.Api/ # API base components
โ โ โ โโโ Controllers/ # BaseController
โ โ โ โโโ Filters/ # ApiExceptionFilter
โ โ โ โโโ Responses/ # ApiResponse
โ โ โ
โ โ โโโ BuildingBlocks.Shared/ # Shared utilities
โ โ
โ โโโ Modules/ # ๐ฆ Business Modules
โ โ โโโ Identity/ # ๐ค Authentication & User Management
โ โ โ โโโ Identity.Domain/ # User, Role entities
โ โ โ โโโ Identity.Application/ # 8 Command/Query handlers
โ โ โ โ โโโ Commands/ # Register, Login, ConfirmEmail, etc.
โ โ โ โ โโโ Queries/ # GetUser, ValidateToken
โ โ โ โโโ Identity.Infrastructure/ # EF Core, IdentityDbContext
โ โ โ โ โโโ Data/ # DbContext, Migrations
โ โ โ โ โโโ Repositories/ # User repositories
โ โ โ โโโ Identity.Api/ # 8 API endpoints
โ โ โ โโโ Controllers/ # AuthenticationController
โ โ โ
โ โ โโโ Catalog/ # ๐ฆ Product & Category Management
โ โ โ โโโ Catalog.Domain/ # Product, Category entities
โ โ โ โ โโโ Entities/ # Domain models
โ โ โ โ โโโ Repositories/ # Repository interfaces
โ โ โ โโโ Catalog.Application/ # CQRS handlers & Specifications
โ โ โ โ โโโ Features/
โ โ โ โ โ โโโ Products/ # Product commands & queries
โ โ โ โ โ โโโ Categories/ # Category commands & queries
โ โ โ โ โโโ Specifications/ # LowStockProducts, ProductsByPrice, etc.
โ โ โ โโโ Catalog.Infrastructure/ # EF Core, CatalogDbContext
โ โ โ โ โโโ Data/ # DbContext, Migrations
โ โ โ โ โโโ Repositories/ # Repository implementations
โ โ โ โโโ Catalog.Api/ # 11 API endpoints
โ โ โ โโโ Controllers/ # ProductsController, CategoriesController
โ โ โ
โ โ โโโ Auditing/ # ๐ Audit Logging
โ โ โโโ Auditing.Domain/ # AuditLog entity
โ โ โโโ Auditing.Application/ # Audit query handlers
โ โ โโโ Auditing.Infrastructure/ # AuditingDbContext
โ โ โ โโโ Data/ # Separate audit schema
โ โ โโโ Auditing.Api/ # 1 API endpoint
โ โ โโโ Controllers/ # AuditLogsController
โ โ
โ โโโ DbMigrator/ # ๐๏ธ Database Migration Tool
โ โ โโโ DbMigrationService.cs # Orchestrates 3 DbContexts
โ โ โโโ MigrationSettings.cs # Configuration model
โ โ โโโ Program.cs # Console app entry point
โ โ โโโ appsettings.json # Migration settings
โ โ โโโ README.md # Migration guide
โ โ โโโ DbMigrator.csproj
โ โ
โ โโโ CleanArchitecture.Api/ # ๐ Main API Gateway
โ โโโ Extensions/ # Module registration
โ โ โโโ IdentityModuleExtensions.cs
โ โ โโโ CatalogModuleExtensions.cs
โ โ โโโ AuditingModuleExtensions.cs
โ โโโ Program.cs # Application entry point
โ โโโ appsettings.json # Configuration
โ โโโ CleanArchitecture.Api.csproj
โ
โโโ docs/ # ๐ Documentation
โ โโโ imgs/
โ โโโ CleanArchitecture-DDD.png
โ
โโโ Directory.Packages.props # ๐ฆ Central package management
โโโ CHANGELOG.md # Version history
โโโ RELEASE_NOTES_v1.0.0.md # v1.0.0 release notes
โโโ QUICK_START_v1.0.0.md # Quick start guide
โโโ ARCHITECTURE.md # Architecture documentation
โโโ README.md # This file
Modular Monolith with Clean Architecture (v1.0.0):
- 18 Projects total across BuildingBlocks, Modules, DbMigrator, and API
- 3 Business Modules (Identity, Catalog, Auditing) with separate schemas
- Custom Dispatcher replacing MediatR for unique identity
- Central Package Management for unified versioning
- Production Tooling with DbMigrator for CI/CD pipelines
- .NET 8 - Latest .NET framework
- ASP.NET Core - Web framework
- Entity Framework Core 8.0.10 - ORM
- Custom Dispatcher - CQRS implementation (replaces MediatR)
- FluentValidation 11.9.0 - Input validation
- Serilog 4.2.0 - Structured logging
- Mapster - Object mapping
- Swagger/Swashbuckle 7.0.0 - API documentation
- SQL Server - Primary database
- In-Memory Database - Testing
- IMemoryCache - In-memory caching
- Redis (Optional) - Distributed caching
- Docker - Containerization
- docker-compose - Multi-container deployment
- xUnit - Testing framework
- Moq - Mocking framework
- GitHub Actions - CI/CD pipeline
-
โ Identity Module - Authentication & User Management (8 API endpoints)
- User registration and login
- JWT token generation & refresh token support
- Email confirmation workflow
- Password reset functionality
- Full CQRS implementation with Custom Dispatcher
-
โ Catalog Module - Product & Category Management (11 API endpoints)
- Product CRUD with category relationships
- Category management with hierarchical support
- CSV export functionality
- Specification Pattern for complex queries
- Full CQRS implementation with Custom Dispatcher
-
โ Auditing Module - Audit Logging (1 API endpoint)
- Centralized audit log storage
- Query with pagination support
- Separate database schema for isolation
-
๐ Authentication & Authorization - Complete JWT-based security
- User login and registration with Identity framework
- Refresh token support
- Role-based authorization ready
- Password validation and security
-
๐ก๏ธ Security Middleware - 8 middleware components:
- GlobalExceptionHandlerMiddleware - Centralized exception handling
- ApiRequestLoggingMiddleware - Request/response logging
- RateLimitingMiddleware - Request throttling (100 req/min default)
- AutoEntityLockMiddleware - Automatic entity locking
- ActionLoggingFilter - Action-level logging
- LoggingStatusCodeMiddleware - Status code logging
- CORS Configuration - Environment-specific policies
- Response Compression - Gzip and Brotli support
-
๏ฟฝ API Features:
- API Versioning (v1.0, v2.0) with Asp.Versioning
- OData support for advanced querying
- Swagger/OpenAPI with enhanced UI
- Health checks (Database & Application)
- XML documentation support
-
๐๏ธ Data Access:
- Entity Framework Core with SQL Server
- Repository pattern implementation
- Unit of Work pattern
- Generic repository with CRUD operations
- Audit logging and entity tracking
-
๏ฟฝ Logging & Monitoring:
- Serilog for structured logging
- File and console logging
- Request/response logging
- Performance monitoring
- Audit log entries tracking
-
๐งช Testing Infrastructure (17 test files):
- Product Tests (6 files): AddOrUpdate, Delete, GetById, Gets, CommandQuery, FeatureSummary
- Category Tests (6 files): AddOrUpdate, Delete, GetById, Gets, CommandQuery, FeatureSummary
- Integration Tests (5 files): Category, Product, Health, Identity, Logs Controllers
-
๐ฏ IDispatcher Interface - Main dispatcher with Query, Command, and DomainEvent methods
- Generic Query for read operations
- Generic Command for write operations
- PublishDomainEvent for domain events
-
โก Automatic Validation - FluentValidation integration in pipeline:
- Validates all commands and queries before execution
- Returns detailed validation errors
- No need for manual validation in handlers
-
๐ Performance Monitoring - Built-in Stopwatch:
- Measures execution time for all operations
- Structured logging with performance metrics
- Helps identify slow queries/commands
-
๐ข Structured Logging - Emoji-based log indicators:
- ๐ Query execution logs
- โก Command execution logs
- ๐ข Domain event publication logs
- Detailed error logging with stack traces
-
๐ง Automatic Handler Registration - Reflection-based discovery:
- AddHandlersFromAssembly() extension method
- Registers all ICommandHandler<,> and IQueryHandler<,>
- Registers all IDomainEventHandler<> implementations
- No manual registration needed
-
๐ฆ Multi-DbContext Support - Orchestrates 3 separate contexts:
- IdentityDbContext (identity schema)
- CatalogDbContext (catalog schema)
- AuditingDbContext (auditing schema)
-
๐ฅ Health Checks - Pre-migration validation:
- Database connectivity tests
- Schema existence verification
- Detailed error reporting
-
๐ Structured Logging - Serilog integration:
- Console output with color-coded levels
- File logging (logs/dbmigrator-.txt)
- Detailed migration progress tracking
-
๐ Idempotent Execution - Safe to run multiple times:
- Applies only pending migrations
- Skips already-applied migrations
- Transaction support
-
๐ CI/CD Ready - Production deployment support:
- Exit codes for automation (0=success, 1=failure)
- Configuration via appsettings.json
- Seed data infrastructure ready
- Directory.Packages.props - Single source of truth for all package versions
- ManagePackageVersionsCentrally - Enabled across all 18 projects
- Organized Groups - Core, EF Core, ASP.NET, Serilog, Testing, Tools
- Version Consistency - No version conflicts between projects
- .NET 8 SDK - Download
- SQL Server or SQL Server Express - Download
- Visual Studio 2022 or VS Code with C# extension
- Git for version control
# Clone the repository
git clone https://github.com/hammond01/CleanArchitecture.git
cd CleanArchitecture
# Update connection string in appsettings.json
# Edit: src/CleanArchitecture.Api/appsettings.json
# ConnectionStrings:DefaultConnection = "Server=YOUR_SERVER;..."
# Run database migrations
dotnet run --project src/DbMigrator
# Or migrate manually for each module:
dotnet ef database update --project src/Modules/Identity/Identity.Infrastructure --startup-project src/CleanArchitecture.Api --context IdentityDbContext
dotnet ef database update --project src/Modules/Catalog/Catalog.Infrastructure --startup-project src/CleanArchitecture.Api --context CatalogDbContext
dotnet ef database update --project src/Modules/Auditing/Auditing.Infrastructure --startup-project src/CleanArchitecture.Api --context AuditingDbContext
# Run the API
dotnet run --project src/CleanArchitecture.Api
# Access Swagger UI
# Open: http://localhost:5000/swagger- CHANGELOG.md - Version history and changes
- RELEASE_NOTES_v1.0.0.md - Complete v1.0.0 release notes (282 lines)
- QUICK_START_v1.0.0.md - Quick reference guide
- DbMigrator README - Database migration guide
- ARCHITECTURE.md - Architecture documentation
All implementations share these common requirements:
- .NET 8 SDK or later
- Visual Studio 2022 or VS Code with C# extension
- SQL Server or SQL Server Express (for database)
- Git for version control
- Docker (optional, for containerized deployments)
- Postman or similar (for API testing)
Identity Module (8 endpoints):
- POST
/api/authentication/register- User registration - POST
/api/authentication/login- User login - POST
/api/authentication/refresh-token- Refresh JWT token - POST
/api/authentication/confirm-email- Email confirmation - POST
/api/authentication/forgot-password- Initiate password reset - POST
/api/authentication/reset-password- Complete password reset - GET
/api/authentication/user- Get user profile - POST
/api/authentication/logout- User logout
Catalog Module (11 endpoints):
- GET
/api/products- List all products - GET
/api/products/{id}- Get product by ID - POST
/api/products- Create product - PUT
/api/products/{id}- Update product - DELETE
/api/products/{id}- Delete product - GET
/api/products/export- Export products to CSV - GET
/api/categories- List all categories - GET
/api/categories/{id}- Get category by ID - POST
/api/categories- Create category - PUT
/api/categories/{id}- Update category - DELETE
/api/categories/{id}- Delete category
Auditing Module (1 endpoint):
- GET
/api/auditlogs- Query audit logs with pagination
-
Create Module Structure in
src/Modules/YourModule/YourModule/ โโโ YourModule.Domain/ โโโ YourModule.Application/ โโโ YourModule.Infrastructure/ โโโ YourModule.Api/ -
Create Domain Entities in
YourModule.Domain/Entities/- Inherit from
Entitybase class from BuildingBlocks.Domain - Implement business rules and domain events
- Inherit from
-
Create Repository Interfaces in
YourModule.Domain/Repositories/- Inherit from
IRepository<T>from BuildingBlocks.Domain
- Inherit from
-
Create Commands/Queries in
YourModule.Application/Features/- Commands implement
ICommand<TResponse> - Queries implement
IQuery<TResponse> - Add FluentValidation validators
- Commands implement
-
Create Handlers in
YourModule.Application/Features/- Command handlers implement
ICommandHandler<TCommand, TResponse> - Query handlers implement
IQueryHandler<TQuery, TResponse> - Use Custom Dispatcher (no MediatR!)
- Command handlers implement
-
Implement Infrastructure in
YourModule.Infrastructure/- Create DbContext inheriting from DbContext
- Implement repositories
- Add migrations:
dotnet ef migrations add InitialCreate
-
Create API Controllers in
YourModule.Api/Controllers/- Inject
IDispatcherfrom BuildingBlocks.Application - Use
dispatcher.Query()ordispatcher.Command()
- Inject
-
Register Module in
src/CleanArchitecture.Api/Extensions/- Create
YourModuleExtensions.cs - Register DbContext, repositories, and handlers
- Call
services.AddHandlersFromAssembly(typeof(YourHandler).Assembly)
- Create
- Create Domain Entity in
ModuleName.Domain/Entities/ - Create Repository Interface in
ModuleName.Domain/Repositories/ - Implement Repository in
ModuleName.Infrastructure/Repositories/ - Create Commands/Queries in
ModuleName.Application/Features/EntityName/ - Create Handlers for Commands/Queries (use
IDispatcher) - Update DbContext to include new
DbSet<Entity> - Create Migration:
dotnet ef migrations add AddEntityName - Create Controller in
ModuleName.Api/Controllers/ - Write Tests (if test infrastructure exists)
- Use C# naming conventions
- Follow Clean Code principles
- Implement proper error handling
- Add comprehensive logging (use Serilog)
- Use Custom Dispatcher (not MediatR)
- Write FluentValidation validators for all commands/queries
- Document public APIs with XML comments
- Follow Modular Monolith principles - keep modules isolated
โ ๏ธ Note: Testing infrastructure is currently in planning phase for v1.0.0. The focus has been on building solid foundation with Custom Dispatcher, DbMigrator, and core business modules.
Unit Testing (Planned):
- Test Custom Dispatcher with mock handlers
- Test CQRS handlers in isolation
- Test domain entities and business rules
- Test FluentValidation validators
- Test Specification Pattern implementations
Integration Testing (Planned):
- Test API endpoints end-to-end
- Test database operations with TestContainers
- Test Custom Dispatcher with real handlers
- Test module integration
Test Infrastructure (To Be Implemented):
- xUnit - Testing framework
- Moq or NSubstitute - Mocking framework
- FluentAssertions - Assertion library
- Testcontainers - Docker-based integration tests
- WebApplicationFactory - API integration tests
# Run all tests
dotnet test
# Run with detailed output
dotnet test --verbosity normal
# Run with coverage report
dotnet test --collect:"XPlat Code Coverage"
# Run specific module tests
dotnet test --filter "FullyQualifiedName~Catalog"- Unit Tests: 80%+ code coverage
- Integration Tests: All API endpoints
- E2E Tests: Critical user flows
- Performance Tests: DbMigrator and Dispatcher benchmarks
- Clean Architecture Guide
- Domain-Driven Design
- API Documentation
- Database Schema
- Development Guide
- Deployment Guide
We welcome all contributions! Please read our Contributing Guidelines for details.
- Fork the project
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the MIT License. See the LICENSE file for details.
- Clean Architecture by Uncle Bob
- Domain-Driven Design by Eric Evans
- .NET Community
- Author: hammond01
- GitHub: https://github.com/hammond01
- Project Link: https://github.com/hammond01/CleanArchitecture
- LinkedIn: Connect with me on LinkedIn
v1.0.0 (February 2026) - โ RELEASED:
- โ Custom CQRS Dispatcher replacing MediatR
- โ DbMigrator production tool
- โ Central Package Management
- โ 3 business modules (Identity, Catalog, Auditing)
- โ 19 working API endpoints
- โ Complete documentation (CHANGELOG, RELEASE_NOTES, QUICK_START)
v1.1.0 (Q2 2026) - ๐ง Planned:
- ๐ Complete authentication workflows (email verification, password reset)
- ๐ Comprehensive testing infrastructure (Unit + Integration tests)
- ๐ API health checks and monitoring endpoints
- ๐ Docker Compose for complete environment
- ๐ CI/CD pipeline with GitHub Actions
v1.2.0 (Q3 2026) - ๐ Planned:
- ๐ Additional business modules (Orders, Inventory, Customers)
- ๐ Advanced querying with Specification Pattern expansion
- ๐ Caching layer (Redis integration)
- ๐ Background job processing
- ๐ API rate limiting and throttling
v2.0.0 (Q4 2026) - ๐ก Future:
- ๐ก Event Sourcing implementation
- ๐ก CQRS with separate read/write databases
- ๐ก Real-time features with SignalR
- ๐ก Advanced security (OAuth2, OpenID Connect)
- ๐ก Multi-tenancy support
This project demonstrates Modular Monolith architecture with a clear path to distributed systems:
-
โ Modular Monolith Foundation (v1.0.0 - Current)
- 3 business modules with separate schemas
- Custom Dispatcher for CQRS
- Production tooling (DbMigrator)
- Clean Architecture with DDD principles
-
๐ Enhanced Modular Monolith (v1.x Future)
- Additional business modules
- Complete testing coverage
- Advanced observability
- Performance optimizations
-
๐ก Future Evolution Options (v2.0+)
- Option A: Event-Driven Modular Monolith (event sourcing within modules)
- Option B: Microservices decomposition (when scaling demands require it)
- Option C: Hybrid approach (some modules as microservices)
| Component | Status | Progress | Details |
|---|---|---|---|
| Custom Dispatcher | โ Complete | 100% | CQRS, Validation, Logging, Perf Monitoring |
| DbMigrator | โ Complete | 100% | Multi-DbContext, Health Checks, CI/CD |
| Central Packages | โ Complete | 100% | 18 projects, unified versioning |
| Identity Module | ๐ก Partial | 70% | 8 endpoints, workflows need completion |
| Catalog Module | โ Complete | 100% | 11 endpoints, full CRUD + Specifications |
| Auditing Module | โ Complete | 100% | 1 endpoint, separate schema |
| Testing | ๐ด Planned | 0% | Infrastructure planned for v1.1.0 |
| Documentation | โ Complete | 100% | README, CHANGELOG, RELEASE_NOTES, QUICK_START |
| Overall Project | ๐ก v1.0.0 | 75% | Production foundation ready |
โญ If this project helped you learn Clean Architecture and modern .NET development, please give it a star! โญ
๐ Follow the project for updates on new architecture implementations! ๐
