Clean Architecture
Clean Architecture is a way to organise a whole project so it stays maintainable as it grows: code is split into Domain, Application, Infrastructure and Api layers, and dependencies only point inwards. This note builds it as a real .NET solution and covers the repository debate, DTO mapping and the MediatR/AutoMapper licence note.
72.1 The problem: everything in one endpoint
- The business rule (total > 0) lives inside the endpoint.
- The Order entity is created and saved straight through the DbContext.
- The entity itself is returned, so costPrice leaks to the customer.
app.MapPost("/orders", async ( OrderInput input, ShopDb db) =>{ if (input.Total <= 0) return Results.BadRequest("Total > 0"); var order = new Order { Customer = input.Customer, Total = input.Total, CostPrice = input.Total * 0.7m }; db.Orders.Add(order); await db.SaveChangesAsync(); return Results.Ok(order);});$ curl -i localhost:5072/orders \ -H "Content-Type: application/json" \ -d '{"customer":"Asha","total":1499}'HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8{"id":1,"customer":"Asha","total":1499,"costPrice":1049.3}72.2 Why is it used?
- A new endpoint (mobile app, admin panel) would copy the rule.
- Testing the rule needs both a database and HTTP.
- Entities go straight into responses and leak internal fields.
- Clean Architecture gives each job its own place, so rules live once and are testable alone.
72.3 The four layers and the dependency rule
| Layer | Holds | Depends on |
|---|---|---|
| Domain | Entities and business rules | Nothing |
| Application | Use cases, interfaces (IOrderRepository), DTOs | Domain |
| Infrastructure | EF Core, DbContext, repository implementations | Application (and Domain) |
| Api | HTTP endpoints, DI setup | Application + Infrastructure |
- Step 1
1.Api (HTTP, DI setup)
- Step 2
2.-> Infrastructure (EF Core, database)
- Step 3
3.-> Application (use cases, interfaces, DTOs)
- Step 4
4.-> Domain (entities + rules)
- Step 5
5.Domain depends on nothing and does not know other layers exist
Project references make the compiler enforce this
72.4 Real solution: 4 projects
- dotnet new sln creates a .slnx file by default in .NET 10.
- Four projects: three class libraries and one web project.
- Project references encode the rule: Application -> Domain, Infrastructure -> Application, Api -> Application + Infrastructure.
- dotnet build compiles them in dependency order.
dotnet new sln -n Shopdotnet new classlib -o src/Shop.Domaindotnet new classlib -o src/Shop.Applicationdotnet new classlib -o src/Shop.Infrastructuredotnet new web -o src/Shop.Apidotnet sln add src/*/*.csproj dotnet add src/Shop.Application \ reference src/Shop.Domaindotnet add src/Shop.Infrastructure \ reference src/Shop.Applicationdotnet add src/Shop.Api reference \ src/Shop.Application src/Shop.Infrastructure$ cat Shop.slnx<Solution> <Folder Name="/src/"> <Project Path="src/Shop.Api/Shop.Api.csproj" /> <Project Path="src/Shop.Application/Shop.Application.csproj" /> <Project Path="src/Shop.Domain/Shop.Domain.csproj" /> <Project Path="src/Shop.Infrastructure/Shop.Infrastructure.csproj" /> </Folder></Solution>$ dotnet build Shop.Domain -> ...\Shop.Domain.dll Shop.Application -> ...\Shop.Application.dll Shop.Infrastructure -> ...\Shop.Infrastructure.dll Shop.Api -> ...\Shop.Api.dllBuild succeeded. 0 Error(s)72.5 Domain: entity + rule
- Private setters: outside code cannot change Total directly.
- The constructor is the only way to create an Order, and it checks total > 0.
- No using for EF Core or ASP.NET: the sign of a clean Domain.
namespace Shop.Domain; public class Order{ public int Id { get; private set; } public string Customer { get; private set; } public decimal Total { get; private set; } public Order(string customer, decimal total) { if (total <= 0) throw new DomainException( "Total must be positive"); Customer = customer; Total = total; }}72.6 Application: interface + DTOs + use case
- IOrderRepository says orders are saved and loaded, not how.
- PlaceOrderRequest and OrderDto records are the only shapes that leave the API.
- OrderService asks only for the interface; the Domain constructor checks the rule, the repository saves, ToDto maps.
using Shop.Domain;namespace Shop.Application; public interface IOrderRepository{ Task AddAsync(Order order); Task<Order?> GetAsync(int id);} public record PlaceOrderRequest( string Customer, decimal Total); public record OrderDto( int Id, string Customer, decimal Total);using Shop.Domain;namespace Shop.Application; public class OrderService(IOrderRepository repo){ public async Task<OrderDto> PlaceAsync( PlaceOrderRequest request) { var order = new Order( request.Customer, request.Total); await repo.AddAsync(order); return order.ToDto(); }}public static class OrderMappings{ public static OrderDto ToDto(this Order o) => new(o.Id, o.Customer, o.Total);}72.7 Infrastructure: EF Core implementation
- OrderRepository takes ShopDbContext and implements IOrderRepository from Application.
- So Infrastructure refers to Application, never the other way round.
- AddAsync adds and calls SaveChangesAsync; GetAsync uses FindAsync.
using Shop.Application;using Shop.Domain;namespace Shop.Infrastructure; public class OrderRepository(ShopDbContext db) : IOrderRepository{ public async Task AddAsync(Order order) { db.Orders.Add(order); await db.SaveChangesAsync(); } public async Task<Order?> GetAsync(int id) => await db.Orders.FindAsync(id);}72.8 Api: thin endpoint
- AddInfrastructure is an extension method that registers the DbContext and repository in DI.
- AddScoped<OrderService>() registers the use case.
- The endpoint only takes the request and hands it to the service; the response has only the DTO's three fields.
using Shop.Application;using Shop.Infrastructure;var builder = WebApplication.CreateBuilder(args);builder.Services.AddInfrastructure( "Data Source=shop.db");builder.Services.AddScoped<OrderService>();var app = builder.Build();app.MapPost("/orders", async ( PlaceOrderRequest req, OrderService orders) =>{ var dto = await orders.PlaceAsync(req); return Results.Created( $"/orders/{dto.Id}", dto);});app.Run();$ curl -i localhost:5072/orders \ -H "Content-Type: application/json" \ -d '{"customer":"Asha","total":1499}'HTTP/1.1 201 CreatedContent-Type: application/json; charset=utf-8Location: /orders/1{"id":1,"customer":"Asha","total":1499}- Step 1
1.Api endpoint receives PlaceOrderRequest
- Step 2
2.OrderService (Application) runs the use case
- Step 3
3.new Order(...) (Domain) checks Total > 0
- Step 4
4.IOrderRepository -> OrderRepository (Infrastructure) saves via EF Core
- Step 5
5.order.ToDto() -> 201 Created with id, customer, total
costPrice never leaves the server
72.9 Checkpoint: DbContext inside Domain?
- Domain has no reference to Infrastructure, so the namespace is not found: build error.
- Adding that reference creates a cycle (Infrastructure already depends on Domain): MSB4006.
- The compiler itself enforces the dependency rule.
using Shop.Infrastructure;namespace Shop.Domain; public static class OrderSaver{ public static void Save( ShopDbContext db, Order order) => db.Add(order);}$ dotnet build src/Shop.DomainOrderSaver.cs(1,12): error CS0234: The type or namespacename 'Infrastructure' does not exist in the namespace 'Shop'OrderSaver.cs(7,9): error CS0246: The type or namespacename 'ShopDbContext' could not be found $ dotnet add src/Shop.Domain reference \ src/Shop.Infrastructure$ dotnet builderror MSB4006: There is a circular dependency in thetarget dependency graph involving target"_GenerateRestoreProjectPathWalk". [Shop.Domain.csproj]Build FAILED.72.10 Common mistake: where does the interface live?
- Wrong: OrderService asks for the concrete OrderRepository, so Application needs Infrastructure and the cycle error returns.
- Right: the interface lives in Application, the EF class in Infrastructure. This is dependency inversion.
// Wrong: Application -> Infrastructure: MSB4006 cycleusing Shop.Infrastructure;namespace Shop.Application; // concrete EF Core classpublic class OrderService( OrderRepository repo) { }// Right: Interface in Application, EF class in Infrastructureusing Shop.Domain;namespace Shop.Application; public interface IOrderRepository{ Task AddAsync(Order order);} public class OrderService( IOrderRepository repo) { }72.11 The repository debate
| Side | Argument |
|---|---|
| Against a repository | DbContext already is a repository + unit of work; a generic repository is extra code that hides EF Core features |
| For a repository | Keeps Application independent of EF Core; a fake repository makes unit tests easy |
| Practical middle path | Avoid generic repositories; use specific repositories, or the DbContext directly in small projects; one rule across the team |
72.12 DTO mapping: by hand vs Mapperly
- By hand: simple and explicit, but boring as fields grow.
- Mapperly is a source generator: [Mapper] + a partial method generate the same code at build time.
- No reflection at runtime; a mismatched DTO (extra Phone) gives a warning and an error at build time.
using Riok.Mapperly.Abstractions;using Shop.Domain;namespace Shop.Application; [Mapper]public static partial class OrderMapper{ public static partial OrderDto ToDto( this Order order);}# obj/.../OrderMapper.g.cs (global:: trimmed)public static partial OrderDto ToDto( this Order order){ var target = new OrderDto( order.Id, order.Customer, order.Total); return target;}# OrderDto me extra: string Phone$ dotnet buildwarning RMG012: The member Phone on the mapping targettype OrderDto was not found on the mapping source type Ordererror RMG013: OrderDto has no accessible constructorwith mappable arguments| Option | How | Note |
|---|---|---|
| By hand (ToDto) | Extension method copies fields | Explicit, no dependency |
| Mapperly | Source generator at build time | No reflection, build-time errors |
| AutoMapper | Reflection-based at runtime | Commercial licence for business use since 2025 |
72.13 Common mistakes
- Thinking Clean Architecture means 4 projects + MediatR + CQRS: its core is just the dependency rule; for a small API, folders in one project are enough.
- Referencing EF Core or ASP.NET from Domain.
- Returning entities instead of DTOs.
- Adding MediatR or AutoMapper without checking the licence: since 2025 both need a commercial licence for business use.
72.14 Rules
- Keep Domain pure: no EF Core, no ASP.NET.
- Interfaces in Application, implementations in Infrastructure.
- Enforce the dependency rule with project references.
- Always return DTOs; map by hand or with Mapperly.
- Build only as many layers as the project needs.
72.15 Interview tips
- Define it: Domain, Application, Infrastructure and Api layers; dependencies only point inwards.
- Say interfaces live in Application and the EF Core implementation in Infrastructure (dependency inversion).
- Mention that separate projects let the compiler enforce the rule through references.
- Add that a repository and MediatR are optional choices, and mention the 2025 licence change.