SkillPilotAI

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.
C#
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);});
Output
$ 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

LayerHoldsDepends on
DomainEntities and business rulesNothing
ApplicationUse cases, interfaces (IOrderRepository), DTOsDomain
InfrastructureEF Core, DbContext, repository implementationsApplication (and Domain)
ApiHTTP endpoints, DI setupApplication + Infrastructure
Dependency rule: arrows point inwards
  1. 1.Api (HTTP, DI setup)

  2. 2.-> Infrastructure (EF Core, database)

  3. 3.-> Application (use cases, interfaces, DTOs)

  4. 4.-> Domain (entities + rules)

  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.
Terminal
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
Output
$ 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>
Output
$ 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.
C#
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.
C#
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);
C#
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();    }}
C#
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.
C#
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.
C#
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();
Output
$ 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}
POST /orders through the layers
  1. 1.Api endpoint receives PlaceOrderRequest

  2. 2.OrderService (Application) runs the use case

  3. 3.new Order(...) (Domain) checks Total > 0

  4. 4.IOrderRepository -> OrderRepository (Infrastructure) saves via EF Core

  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.
C#
using Shop.Infrastructure;namespace Shop.Domain; public static class OrderSaver{    public static void Save(        ShopDbContext db, Order order)        => db.Add(order);}
Output
$ 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.
C#
// Wrong: Application -> Infrastructure: MSB4006 cycleusing Shop.Infrastructure;namespace Shop.Application; // concrete EF Core classpublic class OrderService(    OrderRepository repo) { }
C#
// 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

SideArgument
Against a repositoryDbContext already is a repository + unit of work; a generic repository is extra code that hides EF Core features
For a repositoryKeeps Application independent of EF Core; a fake repository makes unit tests easy
Practical middle pathAvoid 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.
C#
using Riok.Mapperly.Abstractions;using Shop.Domain;namespace Shop.Application; [Mapper]public static partial class OrderMapper{    public static partial OrderDto ToDto(        this Order order);}
Output
# 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;}
Output
# 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
OptionHowNote
By hand (ToDto)Extension method copies fieldsExplicit, no dependency
MapperlySource generator at build timeNo reflection, build-time errors
AutoMapperReflection-based at runtimeCommercial 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

  1. Keep Domain pure: no EF Core, no ASP.NET.
  2. Interfaces in Application, implementations in Infrastructure.
  3. Enforce the dependency rule with project references.
  4. Always return DTOs; map by hand or with Mapperly.
  5. 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.