Course contents

10. Software Architecture Lesson 2 of 10

Clean Architecture

See the dependency rule in 3D: entities and use cases at the centre, interfaces owned by the core, adapters at the edge, and a database swapped without touching rules.

14 minIntermediate9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Clean architecture arranges code in rings: entities, use cases, interface adapters, frameworks and drivers.
  • Source code dependencies point only inward; inner rings know nothing about outer ones.
  • The core declares the interfaces it needs; adapters implement them; the composition root wires them.
  • Runtime calls still go outward, through those interfaces, against the dependency arrows.
  • Infrastructure can be swapped and the core tested alone, at the cost of extra types and mapping.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Clean architecture, described by Robert C. Martin in 2012, organises an application as concentric rings around its business rules:

  • Entities: enterprise-wide business objects and rules (Order, Money).
  • Use cases: application-specific rules that orchestrate entities (PlaceOrder, CancelOrder), plus the interfaces they need from the outside.
  • Interface adapters: code that converts between the use cases and the outside world (endpoints and controllers, presenters, repository and gateway implementations).
  • Frameworks and drivers: ASP.NET Core, EF Core, the database, message brokers, third-party APIs.

One rule governs it, the dependency rule: source code dependencies point only inward. Nothing in an inner ring may name anything in an outer ring. Onion architecture (Jeffrey Palermo, 2008) and hexagonal architecture (Alistair Cockburn, 2005) express the same idea with different pictures.

Why it exists

In a traditional layered application the domain depends on the data layer, so the business rules know about tables, ORMs and connection handling. Database changes ripple into the rules, and the rules cannot be tested without a database. Clean architecture turns that dependency around so the most valuable and stable code, the business rules, depends on nothing volatile. Frameworks, UIs and databases become replaceable details.

How it works

The core owns its interfaces. The use case declares what it needs:

// Shop.Application
public interface IOrderRepository { Task Add(Order order, CancellationToken ct); }
public interface IPaymentGateway { Task<PaymentResult> Charge(Money amount, CancellationToken ct); }

public sealed class PlaceOrder(IOrderRepository orders, IPaymentGateway payments)
{
    public async Task<Guid> Handle(PlaceOrderCommand cmd, CancellationToken ct)
    {
        var order = Order.Place(cmd.CustomerId, cmd.Lines);   // entity rules
        var result = await payments.Charge(order.Total, ct);
        order.MarkPaid(result.Reference);
        await orders.Add(order, ct);
        return order.Id;
    }
}

Adapters implement them. Shop.Infrastructure references Shop.Application and provides SqlOrderRepository : IOrderRepository using EF Core. The Application project has no reference to Infrastructure or to EF Core.

The composition root wires it. The host (Program.cs) is the outermost code and references everything: builder.Services.AddScoped<IOrderRepository, SqlOrderRepository>();. The core receives implementations through constructor injection.

Control flow versus dependency. At runtime PlaceOrder calls the repository, so control flows outward. The source dependency points inward because the call goes through an interface the core declared. This is the dependency inversion principle applied at the architecture level.

Crossing the boundary with data. Data crossing a ring boundary should be in a form the inner ring defines: commands and results for use cases, not HttpRequest objects or EF entities.

When to use it

  • Rich, long-lived business rules that must be tested thoroughly.
  • Systems where infrastructure is expected to change or has several implementations (multiple storage back ends, payment providers per market).
  • Teams that want the domain model free of persistence and transport concerns, often together with domain-driven design.

When not to

  • CRUD applications and small services with little logic: the extra projects, interfaces and mapping outweigh the benefit.
  • Prototypes and short-lived tools.
  • When the team would add interfaces mechanically without understanding why; the ceremony then remains while the benefit does not.

Trade-offs

Choice You gain You pay
Interfaces owned by the core Replaceable infrastructure, fast unit tests One more type per dependency, indirection when reading code
Separate domain and persistence models Domain free of ORM concerns Mapping code and its bugs
Domain mapped directly by EF Core (common compromise) Less mapping Some persistence concerns leak into entities
Projects per ring Compiler-enforced dependency direction Longer builds, more navigation

Alternatives

  • Layered architecture: simpler, but the domain depends on data access.
  • Hexagonal architecture: the same inversion, described as a core with ports and adapters on a driving and a driven side, with no prescribed inner rings.
  • Vertical slice architecture: organise by feature and keep abstraction to what each slice needs; often combined with a clean core for the domain.

Failure modes

  • Interface for everything: one-implementation interfaces for classes that never vary, adding indirection without a seam that is ever used.
  • Leaky core: IQueryable, EF attributes or HttpContext creep into use cases, quietly breaking the rule.
  • Anemic entities: all rules live in use cases; the entity ring holds only data.
  • Mapping bugs: a field added to one model but not mapped to another silently disappears.
  • Folder-only architecture: rings exist as folders in one project, so nothing stops a wrong reference. Use separate projects or architecture tests.

In production

Common .NET layouts are Domain, Application, Infrastructure and Web (or Api) projects. Enforce the direction with project references and an architecture test (NetArchTest, ArchUnitNET) in CI. Keep fast unit tests on use cases with fakes, and run integration tests for the adapters against a real database (for example with Testcontainers), because fakes cannot prove that SQL and mappings are right. Consider letting EF Core map domain entities directly when the mapping cost is not worth it, as a conscious decision.

Common misconceptions

  • "Dependencies inward means calls inward." Calls go outward through interfaces; only source references point in.
  • "Clean architecture means four projects." The rule matters, not the project count. A single project with enforced rules can follow it; four projects with a leaky core do not.
  • "You can swap the database for free." The code change is contained. Data migration, transactions and query behaviour still need work.
  • "Use cases are just services." A use case represents one application action with its own input and output, rather than a grab-bag of methods.

Interview angle

State the dependency rule and draw the rings, then show the inversion: interface in the core, implementation outside, wiring in the composition root. Explain that control flow goes outward while dependencies point inward. Strong answers name the costs (types, mapping, indirection), say when it is overkill, and relate it to hexagonal and onion architecture as variations of the same idea.

Model assumptions

This lesson is a scripted illustration, not a simulation: the queueing engine models running components exchanging requests, while clean architecture is about how source code depends on other source code. Arrows in the scene are source-code dependencies; packets are hand-placed to show either runtime calls or, as pulses, which way a dependency or a change travels. Packets are slowed to 30–60 ms per hop so they can be followed; real in-process calls take microseconds. Project and class names are examples of a typical .NET layout, not the only correct one.

The lesson as textEvery step of the simulation, written out.
  1. 1. Rings around the business rules

    Clean architecture draws the application as concentric rings. The scene is a slice through them: the centre is Entities (Order and its rules), around it Use cases (PlaceOrder), then Interface adapters (endpoints, repositories, gateways) and outermost Frameworks & drivers (ASP.NET Core, PostgreSQL, the payment provider).

    The left half is the side that calls the application; the right half is what the application calls. The closer to the centre, the more stable and valuable the code.

    Scene: Dashed columns show the rings from left to right: frameworks, interface adapters, use cases, entities, then adapters and frameworks again. Order sits in the centre, PlaceOrder and its two interfaces next to it, the endpoint and the database and payment adapters further out.

    Key idea: Business rules sit at the centre; frameworks, databases and the web are details at the edge.

  2. 2. The dependency rule: arrows point inward

    Every arrow is a source-code dependency: “references”. The rule: source code dependencies point only inward. Order references nothing outside itself. PlaceOrder references Order and its own interfaces, never EF Core, never HTTP types.

    Watch the pulses: the endpoint depends on the use case, and the adapters on the right depend on interfaces in the use-case ring. Nothing in the two inner rings points outward, so nothing outside can break them.

    Scene: Pulses travel along four arrows, all toward the centre: from the endpoint to PlaceOrder, from PlaceOrder to Order, and from both right-hand adapters to the interfaces in the use-case ring.

    Key idea: Inner rings never reference outer rings, so details can change without touching the rules.

  3. 3. The core owns its interfaces

    PlaceOrder needs to save orders and take payments, but must not reference the code that does it. So the use-case ring declares the interfaces it needs, IOrderRepository and IPaymentGateway, in the Application project. The Infrastructure project implements them: SqlOrderRepository : IOrderRepository.

    This is dependency inversion: the high-level policy defines the contract, and the low-level detail conforms to it. In a classic layered app the arrow ran from domain to data; here it runs from data to the core.

    Scene: The two interfaces next to PlaceOrder are highlighted as part of the use-case ring; pulses run from SqlOrderRepository and CardPaymentGateway inward to the interfaces they implement.

    Key idea: Interfaces belong to the code that uses them, not the code that implements them.

  4. 4. Control flows out, dependencies point in

    At runtime an order still travels all the way out to the database. POST /orders reaches the endpoint, which calls PlaceOrder. The use case asks Order to apply its rules, then calls IOrderRepository.Add and IPaymentGateway.Charge.

    Those calls leave the core through the interfaces and arrive in the adapters, travelling *against* the arrows. That is the whole trick: the call goes outward, the dependency points inward. (Scripted illustration, slowed down.)

    Scene: A request travels from the shopper through the host and the endpoint to PlaceOrder, which consults Order, then calls out through IOrderRepository to SqlOrderRepository and PostgreSQL, and through IPaymentGateway to the payment provider, before the answer returns.

    Key idea: Runtime calls cross the boundary outward through interfaces the core owns.

  5. 5. Only the outermost ring knows the concrete classes

    Someone has to decide that IOrderRepository means SqlOrderRepository. That happens in the composition root, Program.cs in the host: builder.Services.AddScoped<IOrderRepository, SqlOrderRepository>();.

    The host is the most volatile, most outer piece of code, so it may reference everything. The core gets its collaborators through constructor injection and never asks for a concrete type.

    Scene: Two new arrows run from the ASP.NET Core host to the two concrete adapters: the composition root registers them. No arrow connects PlaceOrder or Order to a concrete adapter.

    Key idea: Concrete implementations are chosen in the composition root, at the very edge.

  6. 6. Swap the database, keep the core

    Orders move from PostgreSQL to a document database. A new adapter, DocumentOrderRepository, implements the same IOrderRepository; the registration in Program.cs changes to point at it.

    The change stays in the two outer rings: one new adapter, one changed line in the host. PlaceOrder and Order are not recompiled for a reason, because nothing they reference changed. (Real migrations still need data moved and behaviour checked, for example transactions and query semantics.)

    Scene: The SQL repository and PostgreSQL are replaced by a document repository and a document database. The new adapter points at the same IOrderRepository interface; the change pulse travels only through the outer adapter and the host, never into the core.

    Key idea: Replacing a detail means writing a new adapter, not editing the business rules.

  7. 7. Test the use case with no infrastructure at all

    The same seam makes the core easy to test. A unit test news up PlaceOrder with an in-memory fake repository and a fake payment gateway, both implementing the core’s interfaces, and calls it directly: no web host, no database, no network.

    Such tests run in milliseconds and pin down the business rules. You still need a few integration tests that run the real adapters against a real database, because fakes cannot prove the SQL is right.

    Scene: A unit test node calls PlaceOrder directly; the use case consults Order and calls an in-memory fake through its interfaces. The host, the database and the payment provider take no part.

    Key idea: Interfaces owned by the core let tests replace every outer ring with fakes.

  8. 8. The price: more types, more mapping

    Clean boundaries cost code. An order now exists as a request DTO at the endpoint, a domain Order in the core and a persistence model in the adapter, with mapping between them, plus an interface for every outside thing the core uses.

    For a CRUD screen with no rules, that is ceremony: three copies of the same fields. The structure pays off when the rules are rich, live long and must be tested hard, or when infrastructure really does change.

    Scene: The endpoint, Order and the document repository are highlighted, each labelled with its own model of an order and the mapping between them.

    Key idea: Clean architecture buys independence with extra types and mapping; spend it where the rules are worth protecting.

  9. 9. Point every arrow at the rules

    Clean architecture keeps layers but bends them into rings: entities and use cases in the middle, adapters and frameworks outside, and every source dependency pointing inward. The core defines interfaces; the edge implements and wires them.

    You get business rules that do not change when the database, the web framework or the payment provider does, and that can be tested alone. You pay with extra types and mapping. Hexagonal architecture is the same idea described as ports and adapters.

    Scene: The whole cross-section: the unit test and the host on the left, PlaceOrder and Order in the centre, the document repository, fakes and payment adapter on the right; every arrow points toward the centre.

    Key idea: Dependencies inward, control flow outward through interfaces the core owns.