Volume 6 · Chapter 1 — Enterprise Application Architecture and Design Patterns
Clean Architecture in .NET
1.1 Introduction
Clean Architecture is an approach to structuring software so that the rules that make the business valuable are kept separate from the technology that happens to deliver them. Frameworks, databases, message brokers, and UI technologies are treated as replaceable details that plug into a stable core, rather than as the foundation the whole system is built on. In a large .NET enterprise system this distinction is what allows a codebase to survive a decade of framework upgrades, cloud migrations, and changing product requirements without a ground-up rewrite.
The central idea, popularised by Robert C. Martin, is theDependency Rule: source code dependencies may only point inward, toward higher-level policy. The domain at the centre knows nothing about the outside world; the outside world depends on abstractions defined by the domain. When teams get this one rule right, testability, maintainability, and flexibility tend to follow as natural consequences rather than as separate goals that have to be engineered in later.
1.2 Core Principles
Clean Architecture is less a rigid folder layout and more a set of principles that constrain how dependencies flow. The principles worth internalising are:
- Business logic independence- domain rules do not import Entity Framework, ASP.NET Core, or any infrastructure type.
- Dependency direction control- inner layers define interfaces; outer layers implement them (Dependency Inversion in the large).
- High testability- because the core has no I/O, the most valuable logic can be unit tested with plain objects and no test doubles for databases or HTTP.
- Framework independence- the framework is a delivery mechanism, not the architecture. You should be able to swap Web API for gRPC without touching a use case.
- Separation of responsibilities- each layer has a single, well-understood reason to change.
1.3 The Layers and the Dependency Rule
A typical Clean Architecture .NET solution is organised into four concentric layers. The arrows in the diagram below showcompile-time dependencies, and every arrow points inward. Notice that Infrastructure depends on Application and Domain, but Domain depends on nothing.
flowchart TB
subgraph Outer["Frameworks & Drivers"]
UI["API / Web / gRPC"]
DB["EF Core / SQL"]
MSG["Service Bus / Kafka"]
end
subgraph App["Application Layer (Use Cases)"]
UC["Commands / Queries / Handlers"]
PORT["Ports (Interfaces)"]
end
subgraph Dom["Domain Layer (Enterprise Rules)"]
ENT["Entities / Value Objects / Domain Events"]
end
UI --> UC
DB --> PORT
MSG --> PORT
UC --> ENT
PORT --> ENT The single most common architectural mistake in .NET codebases is letting the Domain referenceDbContextor anHttpContext. Once that happens the core can no longer be reasoned about or tested in isolation, and the “clean” boundary silently becomes a big ball of mud.
1.4 Domain Layer
The domain layer contains the concepts and rules that would exist even if the software did not: an account has a balance, a payment cannot exceed available funds, an overdrawn account triggers a fee. These rules belong to entities and value objects, not to services or controllers. The domain layer has zero dependencies on other projects.
// Domain layer - no framework references at all.
namespace Banking.Domain;
public sealed class Account
{
private readonly List<Transaction> _transactions = new();
public AccountId Id { get; }
public Money Balance { get; private set; }
public IReadOnlyList<Transaction> Transactions => _transactions;
public Account(AccountId id, Money openingBalance)
{
Id = id;
Balance = openingBalance;
}
// Business invariant lives in the entity, not in a service.
public void Withdraw(Money amount)
{
if (amount.Amount <= 0)
throw new DomainException("Withdrawal must be positive.");
if (amount > Balance)
throw new InsufficientFundsException(Id, amount, Balance);
Balance -= amount;
_transactions.Add(Transaction.Debit(amount));
// Domain event: something the rest of the system may care about.
Raise(new MoneyWithdrawn(Id, amount));
}
}
Entities vs Value Objects
Anentityhas identity that persists over time (anAccountis the same account even after its balance changes). Avalue objectis defined entirely by its attributes and is immutable (Money(100, "USD")equals any otherMoney(100, "USD")). Modelling money as a value object rather than a rawdecimaleliminates a whole class of currency-mismatch and rounding bugs.
1.5 Application Layer
The application layer orchestrates the domain to fulfil specific use cases. It contains no business rules of its own; instead it loads aggregates through repositoryinterfaces, invokes domain behaviour, and coordinates cross-cutting concerns such as transactions. Crucially, the interfaces it depends on (the “ports”) are defined here or in the domain, and implemented in infrastructure.
// Application layer - depends on Domain and on abstractions only.
public sealed record WithdrawCommand(Guid AccountId, decimal Amount, string Currency);
public sealed class WithdrawHandler
{
private readonly IAccountRepository _accounts; // port (interface)
private readonly IUnitOfWork _uow; // port (interface)
public WithdrawHandler(IAccountRepository accounts, IUnitOfWork uow)
{
_accounts = accounts;
_uow = uow;
}
public async Task Handle(WithdrawCommand cmd, CancellationToken ct)
{
var account = await _accounts.GetByIdAsync(new AccountId(cmd.AccountId), ct)
?? throw new NotFoundException(nameof(Account), cmd.AccountId);
account.Withdraw(new Money(cmd.Amount, cmd.Currency)); // pure domain call
await _uow.SaveChangesAsync(ct); // infrastructure detail behind a port
}
}
1.6 Infrastructure Layer
Infrastructure implements the ports declared by the inner layers. This is where Entity Framework Core, HTTP clients, file storage, and message brokers live. Because these classes implement domain-owned interfaces, they can be swapped without the domain or application layers ever knowing.
// Infrastructure layer - implements a Domain-owned interface.
public sealed class EfAccountRepository : IAccountRepository
{
private readonly BankingDbContext _db;
public EfAccountRepository(BankingDbContext db) => _db = db;
public async Task<Account?> GetByIdAsync(AccountId id, CancellationToken ct) =>
await _db.Accounts
.Include(a => a.Transactions)
.FirstOrDefaultAsync(a => a.Id == id, ct);
public void Add(Account account) => _db.Accounts.Add(account);
}
1.7 A Request Flowing Through the Layers
The sequence diagram below traces a single HTTP withdrawal request as it moves from the outermost layer inward and back out. Every inward call crosses a boundary defined by an interface, and the direction of the arrows never contradicts the Dependency Rule.
sequenceDiagram autonumber actor User participant Ctrl as API Controller participant H as WithdrawHandler (App) participant Repo as IAccountRepository participant Ef as EfAccountRepository (Infra) participant Acc as Account (Domain) participant Uow as IUnitOfWork User->>Ctrl: POST /accounts/123/withdraw Ctrl->>H: Handle(WithdrawCommand) H->>Repo: GetByIdAsync(123) Repo->>Ef: (runtime impl) Ef-->>H: Account aggregate H->>Acc: Withdraw(Money) Acc-->>H: OK (raises MoneyWithdrawn) H->>Uow: SaveChangesAsync() Uow-->>H: committed H-->>Ctrl: result Ctrl-->>User: 200 OK
1.8 Dependency Injection Wiring
Clean Architecture depends on the composition root - usuallyProgram.cs- to bind ports to adapters. This is the one place where the outer layers are allowed to know about concrete infrastructure types.
// Composition root (Program.cs) - the only place that knows the concretes.
builder.Services.AddScoped<IAccountRepository, EfAccountRepository>();
builder.Services.AddScoped<IUnitOfWork, EfUnitOfWork>();
builder.Services.AddScoped<WithdrawHandler>();
1.9 Traditional Layering vs Clean Architecture
| Traditional N-Tier | Clean Architecture |
|---|---|
| UI depends on BLL depends on DAL depends on DB | All layers depend inward on the domain |
| Business logic often leaks into the data layer | Business logic is isolated in the domain |
| Hard to test without a database | Core is testable with plain objects |
| Framework choices are structural | Framework choices are replaceable details |
Why is Clean Architecture useful in enterprise systems?
It reduces coupling between business rules and technology, which lets teams change frameworks, databases, and delivery mechanisms without rewriting the core. Because the domain has no I/O, the most valuable logic becomes trivially unit testable, and the architecture communicates intent - a new engineer can find business rules in one predictable place. In practice the payoff is slower decay: the system remains changeable years into its life.
What exactly is the Dependency Rule and how do you enforce it in .NET?
The Dependency Rule states that source code dependencies may only point inward, toward higher-level policy - inner layers must never reference outer layers. In .NET you enforce it structurally with project references: the Domain project references nothing, Application references Domain, and Infrastructure and API reference Application and Domain. You can add an automated guard using an architecture test library such as NetArchTest or ArchUnitNET that fails the build if, say, the Domain assembly ever referencesMicrosoft.EntityFrameworkCore. That turns a design principle into a CI check.
Where do DTOs and mapping belong in Clean Architecture?
Request and response DTOs are part of the boundary, so they live in or adjacent to the Application layer (for command/query models) and the API layer (for transport contracts). Domain entities should not be serialised directly to clients, because that couples your wire format to your internal model and can leak invariants. Mapping between DTOs and domain objects is an application concern; keep it explicit rather than exposing EF entities through the API.
How do you prevent Clean Architecture from becoming unnecessary complexity?
Apply the principles proportionally to the problem. For a small CRUD service, four projects and a mediator can be overkill; the value of Clean Architecture rises with domain complexity and expected lifespan. The guiding question is “does this boundary protect a rule that is likely to change independently?” If not, collapse it. Avoid ceremonial abstractions - a repository that only wrapsDbSetwith no added behaviour is pure overhead. Introduce layers when they earn their keep, and be willing to start with a modular monolith and extract boundaries as the domain reveals itself.
A team says Clean Architecture is slowing them down. How do you respond?
First, separate the principle from its implementation. Often the friction comes from over-layering (too many mapping hops, a repository per table, interfaces with a single implementation) rather than from the Dependency Rule itself. I’d audit where boundaries add real optionality versus where they add ceremony, collapse the ceremonial ones, and keep the boundaries that protect volatile business rules and enable testing. I’d also check whether the pain is actually tooling - slow tests, unclear conventions - and fix that. The goal is maintainable delivery speed over the life of the system, not maximal purity.
1.10 Banking Enterprise Scenario
A retail bank runs a two-decade-old .NET Framework monolith for account management. Rather than a risky rewrite, the team introduces Clean Architecture incrementally: they carve out a Domain project containing pure account and payment rules, wrap the legacy data access behind repository interfaces, and move new use cases into an Application layer. Over eighteen months they migrate the delivery mechanism from ASP.NET MVC to ASP.NET Core and replace a legacy ORM with EF Core - all without rewriting the core business rules, because those rules never depended on the technology in the first place.
Chapter Revision Notes
- Dependencies always point inward toward the domain.
- Business rules live in entities and value objects, not services.
- Ports are interfaces defined by inner layers; adapters implement them.
- The composition root is the only place that knows concrete infrastructure.
- Enforce the Dependency Rule with project references and architecture tests.
- Apply layering proportionally to domain complexity and lifespan.