TL;DR
The one rule: source code dependencies must point only inward, toward higher-level policy. Nothing in an inner circle can know the name of anything in an outer circle — not a class, not a function, not a variable, not any framework artifact. Frameworks, databases, UI, and delivery mechanisms are all details that plug into the business rules; the business rules never plug into them.
A note on the name: "clean architecture" is sometimes used loosely for any well-organized, layered codebase — a usage close to what Onion Architecture describes. This document is about the specific, named pattern Robert C. Martin published in 2012: concentric rings, a Dependency Rule, and a particular vocabulary (Entities, Use Cases, Interface Adapters, Frameworks & Drivers). Where the generic and specific meanings overlap — inward-pointing dependencies, a persistence-ignorant core — that overlap is real and worth knowing about, but the sections below track Martin's specific model.
The core trade-off: you buy long-term independence from frameworks, databases, and delivery mechanisms — the ability to defer and even swap those decisions — at the cost of more indirection, more files, and a steeper on-ramp for a team that hasn't internalized the Dependency Rule. For a small CRUD app with one obvious database and no plan to ever change it, that cost is rarely worth paying. For a system expected to outlive several frameworks and survive changes of technology, team, and delivery mechanism, it usually is.
Origins and the Problem It Solves
Robert C. Martin ("Uncle Bob") published The Clean Architecture on his 8th Light blog in August 2012, and later expanded it into the 2017 book Clean Architecture: A Craftsman's Guide to Software Structure and Design. He described it explicitly as a synthesis — not a wholly new invention — of ideas that had converged from several directions in the preceding decade.
| Predecessor | Author / Year | What it contributed |
|---|---|---|
| Hexagonal (Ports & Adapters) | Alistair Cockburn, 2005 | The application core talks to the outside world only through ports; adapters are swappable. |
| DCI (Data, Context, Interaction) | Trygve Reenskaug & James Coplien | Use cases as first-class objects, separate from the data they operate on. |
| Onion Architecture | Jeffrey Palermo, 2008 | Concentric layers, the domain model at the center, dependencies pointing inward. |
| BCE (Boundary-Control-Entity) | Ivar Jacobson | Separating interface boundaries from control logic from domain entities. |
Martin synthesized these earlier patterns into a unified model, and his book and talks made the resulting vocabulary common in modern system design. The pathology all of them were responding to was the same: business logic that had grown entangled with a specific database, a specific web framework, or a specific UI toolkit, so that changing any of those meant tearing open the rules that actually mattered to the business.
The fix Martin proposed was to name the rule explicitly rather than leave it implicit: draw the system as concentric rings ordered by how likely each is to change for reasons unrelated to the business, and forbid any dependency from pointing outward-to-inward. A controller can depend on a use case interface. A use case can never depend on a controller.
Core Tenets
Four non-negotiable rules define membership in this pattern — miss any one and what you have is a different (often still reasonable) architecture, not Clean Architecture:
- The Dependency Rule. Source code dependencies point only inward. Nothing in an inner ring can name anything in an outer ring.
- Independence from frameworks. The architecture doesn't depend on the existence of some library of feature-laden software. Frameworks are tools, not the shape your system is built around.
- Testability of business rules in isolation. The business rules can be tested without the UI, database, web server, or any other external element.
- Crossing boundaries via abstraction, never concretion. When data crosses a ring boundary, it crosses as a simple data structure, and the interface that owns the abstraction is always defined by — and lives in — the inner ring, even when control flow moves outward. This is the "flow of control vs. source dependency" distinction that trips up most first implementations.
"None of the outer circles' concerns will have any impact on the inner circles." — the entire book compresses to that sentence.
The Rings, In Detail
Entities
Enterprise-wide business rules, encapsulated in objects with methods, or a set of data structures and functions. The least likely thing in the system to change when something external changes — a new web framework should never touch an Entity.
What must never be here
- Anything that mentions HTTP, EF Core, JSON serialization attributes, or a specific database engine.
Use Cases
Application-specific business rules. Orchestrates the flow of data to and from Entities, directing them to use their enterprise business rules to achieve the goal of the use case. Changes here should only be driven by changes to how the application behaves, never by changes to the database schema or the UI framework.
Interface Adapters
Converts data from the format most convenient for Use Cases and Entities into the format most convenient for external agencies (the database, the web). This is where MVC controllers, presenters, and gateway implementations live.
Frameworks & Drivers
The outermost ring: ASP.NET Core itself, EF Core, the database engine, the message broker client library. Generally glue code that communicates to the next ring inward — you write very little code here beyond composition and wiring.
The defining test
For any class, ask: if I deleted the web framework and the database entirely, would this class still compile unmodified? Entities and Use Cases should answer yes. Interface Adapters and Frameworks & Drivers should answer no.
The Central Mechanic: Crossing Boundaries
The one structural trick that makes the whole pattern work is Dependency Inversion at every boundary crossing. Flow of control frequently needs to move outward-to-inward-to-outward within a single request (a controller calls a use case, which needs to fetch data from a repository implemented in the outer ring). The trick: the interface for that repository is declared in the Use Cases ring, and the implementation lives in the outer ring — so the source-code dependency (the using / assembly reference) still points inward, even though the runtime call crosses outward at execution time.
This is exactly what Martin's original diagram illustrated with its small corner sketch: a controller calls a use case's input port; the use case, when finished, calls an output port (an interface it owns); a presenter implements that output port. Control crosses the boundary twice, but the source dependency arrow only ever points one way — inward.
Full Solution Structure and Wiring
A typical .NET solution maps each ring to one or more projects, with project references enforcing the Dependency Rule at compile time — a reference in the wrong direction is a build error, not just a code-review nit.
| Project | Ring | May reference |
|---|---|---|
Orders.Domain | Entities | nothing |
Orders.Application | Use Cases | Orders.Domain |
Orders.Infrastructure | Interface Adapters (data side) | Orders.Application, Orders.Domain |
Orders.Api | Frameworks & Drivers | all of the above |
// Orders.sln folder layout
src/
Orders.Domain/
Entities/Order.cs
ValueObjects/Money.cs
Orders.Application/
Orders/PlaceOrder/PlaceOrderCommand.cs
Orders/PlaceOrder/PlaceOrderHandler.cs
Abstractions/IOrderRepository.cs
Orders.Infrastructure/
Persistence/OrderDbContext.cs
Persistence/SqlOrderRepository.cs
Orders.Api/
Program.cs
Controllers/OrdersController.cs
tests/
Orders.Domain.Tests/
Orders.Application.Tests/
Orders.ArchitectureTests/
// Orders.Api/Program.cs — composition root
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<OrderDbContext>(opt =>
opt.UseSqlServer(builder.Configuration.GetConnectionString("Orders")));
builder.Services.AddScoped<IOrderRepository, SqlOrderRepository>();
builder.Services.AddScoped<PlaceOrderHandler>();
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
A Complete Worked Example: Placing an Order
One small, concrete domain carried through every ring: a customer places an order for line items, and the system must reject orders with no items and reserve stock.
// Orders.Domain/Entities/Order.cs
namespace Orders.Domain.Entities;
public sealed class Order
{
private readonly List<OrderLine> _lines = [];
public Guid Id { get; private set; } = Guid.NewGuid();
public Guid CustomerId { get; private init; }
public IReadOnlyList<OrderLine> Lines => _lines;
public OrderStatus Status { get; private set; } = OrderStatus.Draft;
public static Order Create(Guid customerId, IEnumerable<OrderLine> lines)
{
var order = new Order { CustomerId = customerId };
var materialized = lines.ToList();
if (materialized.Count == 0)
throw new DomainException("An order must contain at least one line.");
order._lines.AddRange(materialized);
order.Status = OrderStatus.Placed;
return order;
}
}
// Orders.Application/Abstractions/IOrderRepository.cs
namespace Orders.Application.Abstractions;
public interface IOrderRepository
{
Task AddAsync(Order order, CancellationToken ct);
}
// Orders.Application/Orders/PlaceOrder/PlaceOrderCommand.cs
public sealed record PlaceOrderCommand(Guid CustomerId, IReadOnlyList<OrderLineDto> Lines);
// Orders.Application/Orders/PlaceOrder/PlaceOrderHandler.cs
public sealed class PlaceOrderHandler(IOrderRepository repository)
{
public async Task<Guid> HandleAsync(PlaceOrderCommand command, CancellationToken ct)
{
var lines = command.Lines.Select(l => new OrderLine(l.Sku, l.Quantity));
var order = Order.Create(command.CustomerId, lines);
await repository.AddAsync(order, ct);
return order.Id;
}
}
// Orders.Infrastructure/Persistence/SqlOrderRepository.cs
public sealed class SqlOrderRepository(OrderDbContext db) : IOrderRepository
{
public async Task AddAsync(Order order, CancellationToken ct)
{
db.Orders.Add(order);
await db.SaveChangesAsync(ct);
}
}
// Orders.Api/Controllers/OrdersController.cs
[ApiController]
[Route("api/orders")]
public sealed class OrdersController(PlaceOrderHandler handler) : ControllerBase
{
[HttpPost]
public async Task<IActionResult> Post(PlaceOrderCommand command, CancellationToken ct)
{
var id = await handler.HandleAsync(command, ct);
return CreatedAtAction(nameof(Post), new { id }, id);
}
}
Runtime Flows
Change-Impact Analysis
The question this pattern is built to answer well: what happens when the core model changes? The taxonomy below classifies changes by which ring originates them and how far the ripple travels.
| Change type | Originates in | Should touch | Should NOT touch |
|---|---|---|---|
| New business rule (e.g. loyalty discount) | Entities / Use Cases | Domain, Application | Infrastructure, Api (usually) |
| Swap SQL Server for Postgres | Interface Adapters | Infrastructure only | Domain, Application, Api contracts |
| Add a GraphQL endpoint alongside REST | Frameworks & Drivers | Api project (new controller/resolver) | Domain, Application |
| Add a required field to an Entity | Entities | Domain, then Application DTOs, then Infrastructure mapping, then Api contract | nothing is exempt — this ripples outward through every ring by design |
Worked walkthrough: adding a discount rule
A pure business-rule change stays contained to Domain and Application — this is the payoff the pattern is sold on, and here it holds.
Worked walkthrough: swapping the persistence engine
The dangerous walkthrough: leaking a persistence entity as a DTO
Sharp edge The subtle failure mode: returning an EF Core-tracked entity directly from a repository into the Use Cases layer, then serializing it straight out through the controller. It compiles. It even works, for a while. But it means the Interface Adapters ring's persistence concerns (lazy-loading proxies, change tracking, navigation properties) have silently become part of what the Use Cases layer depends on — the Dependency Rule is violated in spirit even though no project reference was crossed.
The fix: repositories always return plain Domain objects, never framework-tracked entities, and Use Cases always map to a DTO before anything crosses back out — never pass an Entity through a presenter or controller boundary unmapped.
Testing Strategy Per Component
// Orders.Domain.Tests/OrderTests.cs — pure unit test, no mocks needed
public class OrderTests
{
[Fact]
public void Create_throws_when_no_lines()
{
Action act = () => Order.Create(Guid.NewGuid(), []);
act.Should().Throw<DomainException>()
.WithMessage("An order must contain at least one line.");
}
}
// Orders.Infrastructure.Tests/SqlOrderRepositoryTests.cs — integration, real Postgres via Testcontainers
public class SqlOrderRepositoryTests : IAsyncLifetime
{
private readonly PostgreSqlContainer _container = new PostgreSqlBuilder().Build();
public Task InitializeAsync() => _container.StartAsync();
public Task DisposeAsync() => _container.DisposeAsync().AsTask();
[Fact]
public async Task AddAsync_persists_order_with_lines()
{
await using var db = CreateContext(_container.GetConnectionString());
var repo = new SqlOrderRepository(db);
var order = Order.Create(Guid.NewGuid(), [new OrderLine("SKU-1", 2)]);
await repo.AddAsync(order, CancellationToken.None);
(await db.Orders.CountAsync()).Should().Be(1);
}
}
When To Use It — And When Not To
Use it when
- The system is expected to live for years across multiple framework/database generations.
- Business rules are complex enough to be worth testing in total isolation from I/O.
- Multiple delivery mechanisms (REST + gRPC + a batch job) need to share the same core logic.
Don't use it when
- It's a CRUD app with thin business logic — the extra indirection buys you nothing over EF Core directly in a Minimal API endpoint.
- You have one developer, one deadline, and no expectation the database will ever change.
- The team hasn't internalized dependency inversion — a half-applied Dependency Rule is worse than no rule, because it looks disciplined while quietly not being.
Pros and Cons, Honestly
| Pros | Cons |
|---|---|
| + Business rules testable with zero I/O | − More projects, more files, more indirection for simple features |
| + Framework and database decisions genuinely deferrable | − Steep on-ramp; easy to apply the rule inconsistently |
| + Clear compile-time enforcement via project references | − DTO-mapping boilerplate at every boundary crossing |
| + Change-impact is genuinely more predictable for pure rule changes | − Can become ceremony without the discipline to enforce it (see §9's sharp edge) |
A genuinely contested trade-off: repository interfaces over just using EF Core's DbContext directly
A live, unsettled debate mirrors the Onion doc's repository-vs-EF-Core argument almost exactly: EF Core's DbSet<T> and LINQ already provide a persistence-ignorant enough abstraction for many teams, and wrapping it in a custom IOrderRepository interface can be pure ceremony that never actually gets swapped for a different implementation. Others argue the interface is what makes the Domain and Application projects compile without ever referencing EF Core at all — which is a different, load-bearing guarantee than "this code happens to be swappable." Reasonable engineers land on both sides.
Comparison vs. Adjacent Architectures
| Dimension | Clean Architecture | Onion Architecture | Hexagonal | Vertical Slice |
|---|---|---|---|---|
| Origin / author / year | Robert C. Martin, 2012 | Jeffrey Palermo, 2008 | Alistair Cockburn, 2005 | Jimmy Bogard, ~2018 |
| Primary organizing axis | Concentric rings by volatility | Concentric rings, domain at center | Ports and adapters around a core | Feature, not layer |
| Dependency direction | Strictly inward | Strictly inward | Inward toward the core via ports | No enforced direction between slices |
| Best-fit scenario | Long-lived systems, complex rules, multiple delivery mechanisms | Similar to Clean; often used loosely as a synonym for it | Systems needing many interchangeable adapters (test doubles, multiple UIs) | Fast-moving CRUD-heavy APIs, small teams |
| Main failure mode | Over-application to simple CRUD; leaked entities (§9) | Same over-application risk as Clean | Port explosion for simple systems | Duplicated logic across slices with no home for shared rules |
The distinction between Clean Architecture and Vertical Slice Architecture is frequently framed as feature-based versus layered organization, and the comparison is generally understood to extend to Onion and Hexagonal as well, since they share Clean Architecture's layered philosophy. In .NET specifically, Vertical Slice tends to suit rapid, feature-focused delivery, while Clean Architecture is better suited to large, long-lived applications where business rules must stay insulated from external change. A pragmatic middle path some teams land on is a hybrid: Clean Architecture's layering for the stable core domain, Vertical Slice organization for fast-moving peripheral features.
Common Mistakes and Anti-Patterns
Anemic use cases that just forward to a repository
// ❌ Wrong — the "use case" adds nothing over calling the repository directly
public sealed class GetOrderHandler(IOrderRepository repo)
{
public Task<Order?> HandleAsync(Guid id) => repo.GetByIdAsync(id);
}
// ✅ Right — only introduce a use case when there is real orchestration or a rule to enforce
public sealed class GetOrderHandler(IOrderRepository repo)
{
public async Task<OrderDto> HandleAsync(Guid id)
{
var order = await repo.GetByIdAsync(id)
?? throw new NotFoundException($"Order {id} not found.");
return OrderDto.FromDomain(order);
}
}
Referencing Entity Framework attributes on Domain entities
// ❌ Wrong — Domain project now references Microsoft.EntityFrameworkCore
[Table("Orders")]
public sealed class Order
{
[Key] public Guid Id { get; set; }
}
// ✅ Right — mapping lives in Infrastructure, via Fluent API, not attributes
// Orders.Infrastructure/Persistence/OrderConfiguration.cs
public sealed class OrderConfiguration : IEntityTypeConfiguration<Order>
{
public void Configure(EntityTypeBuilder<Order> builder)
{
builder.ToTable("Orders");
builder.HasKey(o => o.Id);
}
}
Skipping the interface because "there's only one implementation"
Anti-pattern Having the Use Cases layer reference SqlOrderRepository concretely "because we'll never swap databases" reintroduces the exact coupling the Dependency Rule exists to prevent — and it's rarely actually about swapping databases; it's about being able to unit-test the Use Case with an in-memory fake, without spinning up a real database at all.
Adoption Path
- Start by extracting a
Domainproject with zero external references, even before touching the rest of the app. - Introduce one
IRepository-style interface for your busiest aggregate and route existing code through it. - Add an architecture test (§9's failure mode is exactly what this catches) before adding a second use case.
- Migrate feature by feature — Clean Architecture doesn't require a big-bang rewrite.
ADR template scoped to this pattern
# ADR 0004: Adopt Clean Architecture for the Orders service
## Status
Accepted
## Context
Orders has three planned delivery mechanisms (REST, batch import, gRPC)
and business rules expected to grow substantially over the next two years.
## Decision
Adopt Clean Architecture with four projects (Domain, Application,
Infrastructure, Api), enforced by NetArchTest in CI.
## Consequences
+ Business rules testable without a database.
+ New delivery mechanisms are additive, not invasive.
- More projects and DTO-mapping boilerplate for CRUD-only features.
Reference Checklist
- Domain project has zero third-party package references.
- Every repository interface is declared in Application, implemented in Infrastructure.
- No EF Core attributes, no HTTP types, no JSON attributes on Entities.
- Use Cases return DTOs, never Entities, across any boundary.
- An architecture test enforces the Dependency Rule and runs in CI.
- Composition root (
Program.cs) is the only place concrete implementations are chosen. - Business rules have unit tests that run with no database, no HTTP server.
// Orders.ArchitectureTests — enforcing the Dependency Rule with NetArchTest
[Fact]
public void Domain_should_not_depend_on_other_layers()
{
var result = Types.InAssembly(typeof(Order).Assembly)
.Should()
.NotHaveDependencyOnAny("Orders.Application", "Orders.Infrastructure", "Orders.Api")
.GetResult();
result.IsSuccessful.Should().BeTrue();
}
[Fact]
public void Application_should_not_depend_on_infrastructure_or_api()
{
var result = Types.InAssembly(typeof(PlaceOrderHandler).Assembly)
.Should()
.NotHaveDependencyOnAny("Orders.Infrastructure", "Orders.Api")
.GetResult();
result.IsSuccessful.Should().BeTrue();
}
Sources
Primary
- Robert C. Martin, "The Clean Architecture," 8th Light blog, August 13, 2012.
- Robert C. Martin, Clean Architecture: A Craftsman's Guide to Software Structure and Design, Pearson, 2017.
Analysis and comparison
- Herberto Graça, "Clean Architecture: Standing on the shoulders of giants" — traces the Hexagonal/Onion/Clean lineage.
- No Silver Bullet podcast, "Is Clean Architecture Overengineering?" (April 2025) — a fair-minded, hands-on critique from practitioners.
- nadirbad.dev, "Vertical Slice vs Clean Architecture: A Practical Comparison" (Jan 2026) — real-codebase comparison, not just theory.
Tooling
- NetArchTest.Rules — fluent architecture-rule enforcement for .NET, on NuGet.
- ArchUnitNET — a more expressive, diagram-based architecture-testing library for .NET.
- .NET support policy — official Microsoft lifecycle documentation (.NET 10 is the current LTS, supported through November 2028).