Clean Architecture in .NET: Layers That Actually Help

Understand clean architecture in .NET: domain, application, infrastructure, and API layers, the dependency rule, and when it helps vs over-engineering.

Executive Summary: Clean architecture in .NET is one rule with four conventional projects: source dependencies point inward, so the domain knows nothing, the application layer defines use cases and the interfaces (ports) they need, infrastructure implements those interfaces, and the API project composes everything at startup. What the structure buys you is change isolation: rules change without touching the database, the database changes without touching the rules, and both are testable without each other.

The solution that makes people search for this term is two years old and has one project with everything in it, or five projects where all five reference each other in practice. Adding a field to a task touches the entity, three services, two controllers, and a stored procedure someone wrote on a Thursday. Nothing in that codebase is hard to change because it is written badly. It is hard to change because every part depends on every other part. Layering is the discipline that stops that.

Clean architecture in .NET refers to applying the dependency rule from the original clean architecture essay to a .NET solution: concentric layers where source code dependencies point only inward, toward the domain. Microsoft’s own application architecture guide covers the same family of ideas with .NET-shaped examples.

The examples assume .NET SDK 10.0 with C# 14 and refactor the TaskApi, whose domain modeling comes from the object-oriented C# guide and whose data access comes from the EF Core guides.

I have built a clean-arch service that earned its layers and one that only paid for them. The difference comes down to this: the folders are not the architecture. The dependency rule is, and it can live in four projects or in one project with clear boundaries.

The dependency rule: the one sentence that matters

Every idea in this article is one rule applied repeatedly: source code dependencies point inward. The domain has no dependencies at all; the application layer depends on the domain. Infrastructure depends on both; the API depends on all of them. Nothing in the inner circles knows the name of anything in the outer circles:

            +-----------------------------+
            |        API (outermost)      |  controllers, Program.cs
            |  +-----------------------+ |
            |  |     Infrastructure    | |  EF Core, email, HTTP
            |  |  +-----------------+  | |
            |  |  |  Application    |  | |  use cases, interfaces
            |  |  |  +-----------+ |  | |
            |  |  |  |  Domain   | |  | |  entities, rules, zero deps
            |  |  |  +-----------+ |  | |
            |  |  +-----------------+  | |
            |  +-----------------------+ |
            +-----------------------------+

   references flow only inward:  API -> Infra -> App -> Domain

The magic of the rule is what it forbids. The domain cannot reference EF Core, because the domain is the innermost circle. The application layer cannot call an email service directly, because the email service lives outside it. Instead, application defines INotificationSender and infrastructure provides the implementation. The direction of knowledge is the whole design.

The four layers and what lives in each

Applied to the TaskApi, the conventional solution layout looks like this:

TaskApi.sln
  TaskApi.Domain/            entities, no framework references
    Project.cs, TaskItem.cs
  TaskApi.Application/       use cases and ports
    Tasks/CompleteTask.cs
    Common/ITaskRepository.cs
  TaskApi.Infrastructure/    the outside world, implemented
    Persistence/TaskApiContext.cs
    Persistence/TaskRepository.cs
    Notifications/EmailSender.cs
  TaskApi/                   composition and delivery
    Program.cs, Controllers/TasksController.cs
Layer Contains May reference Must not reference
Domain Entities, invariants, pure domain logic Nothing (the BCL only) Any framework, any other project
Application Use cases, their DTOs, interface definitions (ports) Domain EF Core, HTTP, configuration
Infrastructure DbContext, repositories, email, external APIs Application, Domain Application’s internals beyond its interfaces
API Controllers, middleware, Program.cs All three Business rules (it composes, it does not decide)

Read the table as escalating knowledge: each layer outward knows more about the world, and each layer inward knows more about the business.

The dependency rule in actual code

The pattern that makes the rule real is the interface in the application layer, implemented in infrastructure, wired in the API. Application defines what it needs:

// TaskApi.Application/Common/ITaskRepository.cs
public interface ITaskRepository
{
    Task<TaskItem?> FindAsync(Guid id, CancellationToken ct);
    Task SaveAsync(TaskItem task, CancellationToken ct);
}
// TaskApi.Application/Tasks/CompleteTask.cs
public sealed class CompleteTaskHandler(ITaskRepository repository)
{
    public async Task HandleAsync(Guid taskId, CancellationToken ct)
    {
        var task = await repository.FindAsync(taskId, ct)
            ?? throw new TaskNotFoundException(taskId);

        task.Complete();                      // domain logic lives in the entity
        await repository.SaveAsync(task, ct);
    }
}

Infrastructure implements it with EF Core, the DbContext and querying patterns from the EF Core query guide. The API project registers the pair in the container, the composition mechanics of the dependency injection guide:

// TaskApi.Infrastructure/Persistence/TaskRepository.cs
public sealed class TaskRepository(TaskApiContext context) : ITaskRepository
{
    public Task<TaskItem?> FindAsync(Guid id, CancellationToken ct) =>
        context.Tasks.FirstOrDefaultAsync(t => t.Id == id, ct);

    public Task SaveAsync(TaskItem task, CancellationToken ct) =>
        context.SaveChangesAsync(ct);   // the context is already tracking it
}
// TaskApi/Program.cs: the composition root
builder.Services.AddScoped<ITaskRepository, TaskRepository>();
builder.Services.AddScoped<CompleteTaskHandler>();

Notice what the application layer’s code never mentions: DbContext, TaskApiContext, connection strings, or the word Entity. Swap PostgreSQL for SQLite, or the repository for a fake in tests, and the use case does not change. That is the dependency rule paying rent.

What the layers buy, honestly

Three benefits, in the order they show up in practice:

  • Testable rules without infrastructure. The CompleteTaskHandler above tests against a two-method fake in milliseconds, no database involved. Only the repository needs EF Core integration tests.
  • Swappable infrastructure. EF Core to Dapper for one hot query, Postgres to something else, a fake email sender in tests: the inner layers never notice, because they only ever saw interfaces.
  • A compiler-enforced map of change. When a domain rule changes, the compiler lists exactly which layers are affected; when infrastructure changes, nothing above the interface recompiles.

The real costs, which the articles that sell this pattern tend to omit: more projects and files for small features, mapping code between entities and DTOs and persistence models, and a real onboarding overhead, because a new developer must learn where things live before changing anything. On a two-entity service, those costs exceed the churn they prevent.

When it is over-engineering

Signal Layers help Layers are ceremony
Lifespan Years, active product Prototype, event demo, a six-month tool
Logic density Real domain rules, invariants, workflows CRUD over tables, validation only
Team Multiple people, rotation over years One or two people who know every file
Infrastructure churn Database or providers likely to change One database, one deployment target, forever
Change pattern Business rules change more than plumbing Plumbing changes more than rules

The test I apply: take the last ten pull requests. If most of them changed business rules and got slowed by unrelated coupling, the dependency rule pays for itself. If most of them added columns and endpoints to a stable schema, layers only added hops.

Feature folders: the working alternative

Vertical slice architecture answers the same problem from the other end: organize by feature instead of by technical role. One folder per feature holds its endpoint, handler, DTOs, and EF Core mapping, and nothing else shares it:

TaskApi/Features/Tasks/
  TasksController.cs
  CompleteTask.cs        // handler + endpoint, EF Core directly
  TaskContracts.cs        // request and response records
  TaskMapping.cs          // entity configuration
TaskApi/Features/Projects/
  ...same shape, no shared "services" project

Slices trade layer isolation for feature isolation: one feature’s code changes without touching another’s, queries live next to the endpoints that call them (the projection patterns from the query guide). There is no mapping ceremony between layers. What you lose is the hard boundary between domain logic and infrastructure, so the discipline shifts from project references to conventions and reviews. For medium services with feature-sized change patterns, slices are the pragmatic middle. Layered clean architecture earns its structure at larger scales where the boundary needs to be compiler-enforced.

MediatR: check the license before you standardize

Most clean architecture templates in the .NET ecosystem ship with MediatR, the in-process mediator that wires requests to handlers, so this is the paragraph where that choice needs a caution. MediatR’s current major versions are distributed under a commercial license by Lucky Penny Software, requiring a license key configured in code or through environment variables, with registration at MediatR.io. That is a legitimate business decision by its maintainers. However, it changes the calculus for a foundation your whole application structure leans on. Verify the current license terms on the MediatR repository against your commercial use before adopting. Or choose plain handler classes registered in the container, which the pattern above shows without any mediator at all. The dependency rule does not need a mediator to work; it needs interfaces that point the right way.

How real systems do this

  • Layer boundaries verified by build rules. Large solutions enforce the dependency rule mechanically: the domain project’s references are reviewed like security settings, because one Microsoft.EntityFrameworkCore reference in Domain quietly undoes the circle.
  • Extension methods compose the root. Each layer exposes AddInfrastructure() and AddApplication() style extensions. So Program.cs stays a readable list of which circles are wired in. The DI guide covers the registration mechanics.
  • The shape matches the team, not the trend. Long-lived core services get four projects. Small internal APIs get feature folders in one project. The shared rule in both is that dependencies point at the domain.

A refactor I remember was exactly the before-picture: a five-project solution where a single new status field on a task touched every project, because the entities were shared, mapped three times, and validated in two layers. The team’s instinct was to add a sixth project for the new feature. What actually helped was redrawing the boundaries: entities and rules into the innermost layer, mapping confined to the outermost, and one interface where the crossing had to happen. Afterward the same change touched two files. What stuck with me: layers do not reduce coupling automatically; only the direction of the dependencies does.

Decision framework: four projects, one project, or slices

  1. How long will this code live? Years: the boundary discipline pays. Months: pick the layout with the fewest files that still keeps rules out of controllers.
  2. Where does the change happen? Rules change weekly: layers protect the hot spot. Features change independently: slices protect the hot spot.
  3. Who enforces the boundary? A compiler can (project references) or the team can (conventions). Choose the enforcement you will actually maintain.
  4. Does every layer earn its mapping cost? If two layers always change together, they are one layer wearing two project files.
  5. What would a new joiner touch first? Whichever structure makes the first safe change easiest is the right one for your team’s actual future.

When NOT to use layered clean architecture

  • CRUD services with stable schemas. Table maintenance behind an API needs contracts and validation, not four projects. The layers would carry one query each.
  • Prototypes and short-lived tools. You will know the layout was wrong only when the tool survives; until then, spend the time on the product.
  • Team of one, known codebase. The boundary’s benefit is shared understanding at scale. One developer who knows every line already has it.

Common mistakes

  • Domain referencing a framework “just for annotations”. One EF Core reference in the domain project makes the entities persistence-aware and drags the whole circle outward. Keep the domain to plain C#.
  • Putting domain entities into API responses. The layers leak outward the moment the entity serializes. The boundary rules from the Web API track apply: DTOs cross, entities stay.
  • Interface explosion. One interface per class, created by reflex, adds indirection with no seam. Extract interfaces where the boundary is real: infrastructure and cross-cutting contracts.
  • Copying a template without the rule. Four empty projects with mutual references give you the folder count and none of the protection. The dependency direction is the entire product.
  • Mapping for its own sake. Three identical classes with three mapping profiles is the ceremony version; when two layers always change together, merge them.
  • Standardizing on a library without checking its license. MediatR’s commercial licensing is the current example. Foundations deserve a license review like dependencies deserve a vulnerability one.

Key takeaways

  • Clean architecture is one rule: source dependencies point inward, toward the domain, which knows nothing else.
  • The conventional .NET shape is four layers: Domain (entities, no references), Application (use cases, ports), Infrastructure (implementations), API (composition).
  • Interfaces in the application layer, implemented in infrastructure and wired in the API’s composition root, are the mechanism that enforces the rule.
  • The layers pay off on long-lived, rule-dense systems and are ceremony on CRUD services and prototypes. The last ten pull requests tell you which you have.
  • Feature folders trade layer isolation for feature isolation and are the pragmatic middle for medium services. The dependency direction still applies inside each slice.
  • MediatR’s current major versions are commercially licensed by Lucky Penny Software: verify before standardizing, or use plain container-registered handlers.

FAQ

What is clean architecture in .NET?

A way of organizing a solution around the dependency rule: source code dependencies point only inward. The domain layer has no framework references, the application layer holds use cases and the interfaces they need, infrastructure implements those interfaces, and the API composes everything. The goal is that business rules change without touching infrastructure, and infrastructure changes without touching business rules.

What is the dependency rule?

The rule that source code in an inner layer may not reference anything in an outer layer. Applied outward from the domain, it means the domain compiles alone, the application layer knows only the domain. Infrastructure is the only place the database and outside world appear. Crossing outward-to-inward happens through interfaces defined inward and implemented outward, which is why the composition root wires them together.

What is the difference between clean architecture and vertical slice architecture?

Clean architecture organizes by technical layer, so all controllers live together and all persistence lives together, with interfaces between them. Vertical slices organize by feature, so each feature’s endpoint, logic, and data access share one folder and touch no other feature. Layers suit rule-dense systems with stable features; slices suit services that change feature by feature. Both work when dependencies point at the business logic.

When should I not use clean architecture?

For CRUD services with stable schemas, short-lived tools, and prototypes: the four-project structure adds files, mapping, and onboarding overhead that those systems never pay back. Use contracts, validation, and a clean composition root, and save the layers for code that will live for years and change weekly.

Is MediatR free to use?

Not in its current major versions. MediatR is now distributed by Lucky Penny Software under a commercial license that requires a license key in code or configuration, registered at MediatR.io. Verify the current terms for your use before adopting it, or skip the mediator entirely: plain handler classes registered in the dependency injection container implement the same pattern with no license dependency.

Point the dependencies at the domain

Layers, slices, and single projects all deliver the same architecture when the dependency rule holds: business rules in the middle, plumbing at the edges, interfaces at the crossing points, and a composition root that ties them together. Choose the structure your team will actually maintain, and let the compiler carry the discipline. The operations track continues next with logging in .NET with Serilog, and every guide in the series lives on the .NET series index. The rule of thumb: the folder names are optional; the direction of the dependencies is the architecture.

Last updated on 20 November 2026

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *