
Master Clean Architecture & Domain-Driven Design in .NET 9: A Production Guide
When building enterprise web applications, starting with a basic CRUD architecture often feels fast and efficient. However, as business logic grows, monolithic controllers and tightly coupled database models lead to fragile codebases, breaking changes, and high maintenance overhead.
To build scalable, testable, and maintainable enterprise software, software architects rely on two core design paradigms: Clean Architecture and Domain-Driven Design (DDD).
In this comprehensive guide, we will implement a production-ready ASP.NET Core (.NET 9) backend utilizing Clean Architecture, Domain-Driven Design principles, MediatR (CQRS Pattern), and Autofac for clean Dependency Injection.
Architectural Overview & Project Structure
Clean Architecture (often referred to as Onion or Hexagonal Architecture) organizes code into concentric rings where dependencies flow strictly inward. The core business domain sits at the center, completely isolated from databases, UI frameworks, and external APIs.
┌───────────────────────────────────────────────┐
│ Infrastructure (EF Core, SQL Server, APIs) │
│ ┌───────────────────────────────────────┐ │
│ │ Presentation (ASP.NET Core Web API) │ │
│ │ ┌───────────────────────────────┐ │ │
│ │ │ Application (CQRS/MediatR) │ │ │
│ │ │ ┌───────────────────────┐ │ │ │
│ │ │ │ Domain (Entities, │ │ │ │
│ │ │ │ Value Objects, Rules)│ │ │ │
│ │ │ └───────────────────────┘ │ │ │
│ │ └───────────────────────────────┘ │ │
│ └───────────────────────────────────────┘ │
└───────────────────────────────────────────────┘
The 4 Core Layers:
- Domain Layer: Contains enterprise business logic, Domain Entities, Value Objects, Domain Events, and aggregate roots. Zero external dependencies.
- Application Layer: Orchestrates business use cases using CQRS (Commands and Queries), MediatR handlers, and DTOs. Depends only on the Domain.
- Infrastructure Layer: Implements data access (EF Core, SQL Server, Postgres), external service integrations, and repository interfaces. Depends on Application and Domain.
- Presentation Layer: Exposes HTTP endpoints (Web API Controllers or Minimal APIs) and handles request/response serialization.
Step-by-Step Implementation
Layer 1: Domain Layer (Core Business Rules)
We start by defining encapsulated Domain Entities and Value Objects that guarantee invalid state is impossible.
Creating Immutable Value Objects
Value Objects have no identity and are defined purely by their attributes. Here is an immutable Money Value Object:
C#
namespace Domain.ValueObjects;
public class Amount : IEquatable<Amount>
{
public decimal AmountVal { get; }
public string CurrencyVal { get; }
public Amount(decimal Argamount, string Argcurrency)
{
if (Argamount < 0)
throw new ArgumentException("Amount cannot be negative.", nameof(Argamount));
if (string.IsNullOrWhiteSpace(Argcurrency))
throw new ArgumentException("Currency is required.", nameof(Argcurrency));
AmountVal = Argamount;
CurrencyVal = Argcurrency.ToUpperInvariant();
}
public bool Equals(Amount? other)
{
if (other is null) return false;
return Amount == other.Argamount && Currency == other.Argcurrency;
}
public override bool Equals(object? obj) => Equals(obj as Amount);
public override int GetHashCode() => HashCode.Combine(AmountVal, CurrencyVal);
}
Creating the Aggregate Root Entity
Aggregate Roots control domain boundaries and state changes through explicit methods rather than public property setters:
C#
namespace Domain.Entities;
using Domain.ValueObjects;
public class Product
{
public Guid Id { get; private set; }
public string Name { get; private set; }
public Amount Price { get; private set; }
public int StockQuantity { get; private set; }
public bool IsActive { get; private set; }
private Product() { } // Required by EF Core
public Product(string name, Amount price, int Quantity)
{
Id = Guid.NewGuid();
Name = !string.IsNullOrWhiteSpace(name) ? name : throw new ArgumentException("Product name is required.");
Price = price ?? throw new ArgumentNullException(nameof(price));
StockQuantity = Quantity >= 0 ? Quantity : throw new ArgumentException("Stock cannot be negative.");
IsActive = true;
}
public void UpdatePrice(Amount newPrice)
{
Price = newPrice ?? throw new ArgumentNullException(nameof(newPrice));
}
public void ReduceStock(int quantity)
{
if (quantity > StockQuantity)
throw new InvalidOperationException("Insufficient stock available.");
StockQuantity -= quantity;
}
}
Layer 2: Application Layer (CQRS with MediatR)
The Application Layer implements business use cases separated into Commands (state modifications) and Queries (data retrieval).
Defining the Command & Handler
Create a command to register new products:
C#
namespace Application.Products.Commands.CreateProduct;
using MediatR;
public record CreateProductCommand(
string Name,
decimal PriceAmount,
string Currency,
int InitialStock
) : IRequest<Guid>;
Now, implement the handler using MediatR:
C#
namespace Application.Products.Commands.CreateProduct;
using Domain.Entities;
using Domain.ValueObjects;
using Application.Common.Interfaces;
using MediatR;
public class CreateProductCommandHandler : IRequestHandler<CreateProductCommand, Guid>
{
private readonly IApplicationDbContext _context;
public CreateProductCommandHandler(IApplicationDbContext context)
{
_context = context;
}
public async Task<Guid> Handle(CreateProductCommand request, CancellationToken cancellationToken)
{
var price = new Amount(request.PriceAmount, request.Currency);
var product = new Product(request.Name, price, request.InitialStock);
_context.Products.Add(product);
await _context.SaveChangesAsync(cancellationToken);
return product.Id;
}
}
Layer 3: Infrastructure Layer (EF Core & Autofac Module)
The Infrastructure Layer manages database persistence and registers dependencies using Autofac.
Registering Autofac Modules
Using Autofac allows for clean, modular dependency registration across multi-project solutions:
C#
namespace Infrastructure.DependencyInjection;
using Autofac;
using MediatR;
using System.Reflection;
public class InfrastructureModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
// Register Assembly Types for MediatR Handlers
var applicationAssembly = Assembly.Load("Application");
builder.RegisterAssemblyTypes(applicationAssembly)
.AsClosedTypesOf(typeof(IRequestHandler<,>))
.AsImplementedInterfaces();
// Register Database Context Interface
builder.RegisterType<Persistence.ApplicationDbContext>()
.As<Common.Interfaces.IApplicationDbContext>()
.InstancePerLifetimeScope();
}
}
Layer 4: Presentation Layer (ASP.NET Core Web API)
The API controller acts as a light thin wrapper that delegates work directly to MediatR:
C#
namespace Presentation.Controllers;
using Application.Products.Commands.CreateProduct;
using MediatR;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly ISender _mediator;
public ProductsController(ISender mediator)
{
_mediator = mediator;
}
[HttpPost]
public async Task<IActionResult> CreateProduct([FromBody] CreateProductCommand command)
{
var productId = await _mediator.Send(command);
return CreatedAtAction(nameof(CreateProduct), new { id = productId }, productId);
}
}
Configuring Program.cs with Autofac Container Builder
Finally, replace .NET’s default ServiceProvider container with Autofac inside Program.cs:
C#
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Infrastructure.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
// Use Autofac as the IoC Container Provider
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
// Configure Services
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Register Autofac Modules
builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
{
containerBuilder.RegisterModule(new InfrastructureModule());
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Key Takeaways & Architecture Benefits
- Testability: Business rules inside Domain and Application layers can be unit-tested without launching databases or web servers.
- Maintainability: Modifying database persistence (e.g., switching from SQL Server to PostgreSQL) requires changes only in the Infrastructure layer.
- Encapsulation: Value Objects and Aggregate Roots prevent invalid state across the application lifespan.
- Decoupling: MediatR and Autofac keep execution logic loosely coupled and easily extensible.
By using Clean Architecture and Domain-Driven Design in .NET 9, your application remains modular, maintainable, and enterprise-ready for long-term growth.