Explains Clean Architecture's four layers, the dependency rule and dependency inversion that make the domain independent of infrastructure, and a typical .NET 10 solution layout with its trade-offs.
Clean Architecture (Robert C. Martin, 2012) arranges code in concentric layers with one rule: source code dependencies point inwards.
IOrderRepository or IEmailSender.The key move is dependency inversion: the database depends on the domain, not the other way round. The trade-off: testable, technology-independent rules in exchange for more projects, interfaces and mapping — overkill for simple CRUD.
"Clean Architecture is about one rule: source code dependencies point inwards, towards the business rules. In the middle is the Domain — entities like
Order, value objects likeMoney, domain events and invariants — and it references nothing technical. Around it is Application, which holds the use cases: aPlaceOrdercommand and its handler, and the interfaces that use case needs from the outside world, likeIOrderRepositoryorIPaymentGateway. Outside that is Infrastructure, which implements those interfaces with EF Core, Azure Service Bus, Blob Storage and so on, and Presentation — the ASP.NET Core API — which translates HTTP into use-case calls and contains the composition root inProgram.cs.The trick that makes it work is dependency inversion. In classic layering, business logic references data access. Here the Application project owns the interface and Infrastructure references Application to implement it. So the arrow from business to database is reversed: the database is a plug-in to the rules. In a .NET solution that's four projects —
Domain,Application,Infrastructure,Api— withDomainhaving no project references at all, and an architecture test that fails the build ifDomainever referencesMicrosoft.EntityFrameworkCore.The mistake I see is cargo-culting the template: an anaemic domain, a repository interface per table, and a DTO mapped four times for a CRUD screen. Clean Architecture pays off when the domain has real rules and a long life; for a simple admin app it's ceremony. I'd say: invert the dependencies that protect your important rules, and don't add a layer that has nothing to protect."
| Layer | Contains | References | Must not contain |
|---|---|---|---|
| Domain | Entities, value objects, domain events, domain services, domain errors | Nothing (maybe a small shared kernel) | EF Core, HTTP, logging frameworks |
| Application | Commands, queries, handlers, validators, ports (interfaces), DTOs | Domain | DbContext implementations, HttpContext |
| Infrastructure | DbContext, EF configurations, migrations, repositories, email, messaging, Key Vault clients |
Application, Domain | Business rules |
| Presentation | Endpoints/controllers, auth setup, ProblemDetails, composition root | Application (Infrastructure only for DI registration) | Business rules, SQL |
| Classic layered | Clean | |
|---|---|---|
| Business depends on | Data access | Nothing technical |
| Who owns the repository interface | Data layer | Application (or Domain) |
| Test rules without SQL | Hard | Easy: fake the port |
| Projects | 3 | 4+ |
| Factor | Clean fits | Clean is overkill |
|---|---|---|
| Domain complexity | Real invariants and workflows | Forms over tables |
| Lifetime | Years, many changes | Short-lived or throwaway |
| Team size | 3+ developers working in parallel | One developer |
| Infrastructure churn | Likely to swap or add providers | One database, forever |
In an insurance quoting service, pricing rules lived in the Domain project with no infrastructure references. The team ran 1,400 rule tests in under 4 seconds with no database, and when the rating data moved from SQL Server to a vendor API, only one Infrastructure class and its DI registration changed — the Domain and Application projects were untouched.
Checks that the candidate understands the dependency rule and dependency inversion behind Clean Architecture, not just the folder names, and knows when it is overkill.
Green flags
IEntityTypeConfiguration<T>Red flags
+--------------------------------------------------+
| Presentation (Api) Infrastructure |
| endpoints, Program.cs EF Core, Service Bus, |
| Blob, email |
| +------------------------------------------+ |
| | Application | |
| | commands, queries, handlers, ports | |
| | +----------------------------------+ | |
| | | Domain | | |
| | | entities, value objects, events | | |
| | +----------------------------------+ | |
| +------------------------------------------+ |
+--------------------------------------------------+
all arrows point inwards --> centre
Classic: Business → Data. Clean: the Application project declares
Application: interface IOrderRepository { ... } <-- owned here
Infrastructure: class EfOrderRepository : IOrderRepository (references Application)
At compile time Infrastructure depends on Application. At run time, Application calls Infrastructure through the interface. The flow of control goes outwards, the source dependency goes inwards. The composition root (Program.cs) is the only place that knows both.
Shop.Api ----------> Shop.Application ----> Shop.Domain
| ^
+-----> Shop.Infrastructure (references Application, Domain)
Shop.Domain.csproj: no project or framework references beyond the base library.Shop.Application.csproj: references Domain; may use Microsoft.Extensions.DependencyInjection.Abstractions and FluentValidation.Shop.Infrastructure.csproj: references Application; packages for EF Core, Azure SDKs.Shop.Api.csproj: references Application and Infrastructure (the latter only so Program.cs can call AddInfrastructure()).Two honest schools:
DbContext lives only in Infrastructure.IAppDbContext exposing DbSet<T>, accepting a dependency on EF Core abstractions in exchange for using LINQ in handlers.Both are defensible; the pragmatic one is common in .NET templates. What matters is that the Domain never references EF Core, and mapping is done with IEntityTypeConfiguration<T> in Infrastructure rather than attributes on entities.
Templates (for example, the widely used Clean Architecture templates for .NET) give you the folders. They don't give you a rich domain, sensible aggregate boundaries or a reason for each interface. Teams that only adopt the folders get the costs without the benefits.
dotnet new classlib/webapi and wire references as above; confirm Domain builds with no references.Shop.Domain references Microsoft.EntityFrameworkCore.IOrderRepository and time the suite.Program.cs and confirm no other project changes.The key pieces of a Clean Architecture slice: a rich entity, a port owned by Application, an Infrastructure adapter, and the composition root.
// Shop.Domain/Orders/Order.cs — no framework references
namespace Shop.Domain.Orders;
public sealed class Order
{
private readonly List<OrderLine> _lines = [];
private Order() { } // for EF Core materialisation
public Guid Id { get; private set; } = Guid.NewGuid();
public OrderStatus Status { get; private set; } = OrderStatus.Draft;
public IReadOnlyList<OrderLine> Lines => _lines;
public static Order Create() => new();
public void AddLine(string sku, int quantity, decimal unitPrice)
{
if (Status != OrderStatus.Draft)
throw new InvalidOperationException("Only draft orders can change."); // invariant lives in the domain
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(quantity);
_lines.Add(new OrderLine(sku, quantity, unitPrice));
}
}
public sealed record OrderLine(string Sku, int Quantity, decimal UnitPrice);
public enum OrderStatus { Draft, Placed, Cancelled }
// Shop.Application/Orders/AddOrderLine.cs — the use case and the port it needs
namespace Shop.Application.Orders;
using Shop.Domain.Orders;
public interface IOrderRepository // port: owned by Application, implemented by Infrastructure
{
Task<Order?> GetAsync(Guid id, CancellationToken ct);
Task SaveChangesAsync(CancellationToken ct);
}
public sealed record AddOrderLineCommand(Guid OrderId, string Sku, int Quantity, decimal UnitPrice);
public sealed class AddOrderLineHandler(IOrderRepository orders)
{
public async Task<bool> HandleAsync(AddOrderLineCommand cmd, CancellationToken ct)
{
var order = await orders.GetAsync(cmd.OrderId, ct);
if (order is null) return false;
order.AddLine(cmd.Sku, cmd.Quantity, cmd.UnitPrice);
await orders.SaveChangesAsync(ct);
return true;
}
}
// Shop.Infrastructure/Persistence/EfOrderRepository.cs — adapter (references Application)
namespace Shop.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Shop.Application.Orders;
using Shop.Domain.Orders;
internal sealed class EfOrderRepository(ShopDbContext db) : IOrderRepository
{
public Task<Order?> GetAsync(Guid id, CancellationToken ct) =>
db.Orders.Include(o => o.Lines).SingleOrDefaultAsync(o => o.Id == id, ct);
public Task SaveChangesAsync(CancellationToken ct) => db.SaveChangesAsync(ct);
}
public static class InfrastructureRegistration
{
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration config)
{
services.AddDbContext<ShopDbContext>(o => o.UseSqlServer(config.GetConnectionString("Shop")));
services.AddScoped<IOrderRepository, EfOrderRepository>();
return services;
}
}
// Shop.Api/Program.cs — composition root
using Shop.Application.Orders;
using Shop.Infrastructure.Persistence;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddInfrastructure(builder.Configuration);
builder.Services.AddScoped<AddOrderLineHandler>();
var app = builder.Build();
app.MapPost("/orders/{id:guid}/lines", async (Guid id, AddOrderLineCommand body, AddOrderLineHandler handler, CancellationToken ct) =>
await handler.HandleAsync(body with { OrderId = id }, ct) ? Results.NoContent() : Results.NotFound());
app.Run();
IAppDbContext compromise and document it.virtual navigation properties on domain entities. Why it is wrong: persistence concerns leak into the core. Instead: configure mapping with IEntityTypeConfiguration<T> in Infrastructure.The value of Clean Architecture is not the four folders; it is that the code you most need to get right has no dependency on the code most likely to change. That's worth a lot in a complex, long-lived domain and almost nothing in a CRUD app. I invert dependencies at the real boundaries — persistence, messaging, external APIs, time — and resist interfaces everywhere else. I also accept pragmatic compromises (an IAppDbContext in Application) when the team agrees and records them in an ADR.
Two details separate a senior answer. First, the composition root (Program.cs plus each project's AddXxx() extension) is the only place that knows both an abstraction and its implementation; nothing else resolves from the container, which is what keeps the layers decoupled at run time as well as compile time. Second, infrastructure churn should stop at the port: when a provider changes (SQL Server to a vendor API, SMTP to Azure Communication Services) you change an adapter and a registration; if the change forces domain edits, the port was shaped around the old technology and needs redesigning in domain terms.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Full Clean (pure ports) | Complex domain, likely infrastructure change, large team | Most interfaces and mapping | CRUD-heavy apps |
Pragmatic Clean (IAppDbContext) |
Rich domain, EF Core is a settled choice | Application tied to EF Core abstractions | When you must swap persistence |
| Vertical slice | Many independent features, simple rules each | Less shared structure | Rules shared across many features |
Measure the payoff: how fast the domain tests run without a database, and how many projects change for a typical feature.
I decide by what the abstraction protects, not by habit. DbContext is already a repository and unit of work, so a wrapper has to earn its place.
DbContext with Select and AsNoTracking. Never return IQueryable from a repository.ExecuteUpdateAsync/ExecuteDeleteAsync bypass the change tracker and run at once, so they belong behind an intention-revealing method and need an explicit transaction to be atomic with SaveChanges.My answer flips for pure CRUD (skip repositories) or for Dapper, stored procedures or a second store (repositories hide them). The trade-off is domain protection against a layer that only renames EF Core.
The composition root is the single place where the application's object graph is wired up: in ASP.NET Core, Program.cs and the AddXxx() extension methods it calls. It is the only code that knows about concrete implementations and the container.
Everything else asks for what it needs through its constructor. If business classes call IServiceProvider.GetService themselves, that is the service locator anti-pattern: their dependencies are hidden from the signature, a missing registration only shows up at run time, and unit tests need a container instead of a couple of fakes. Keeping resolution in the root keeps business code independent of the container, easier to test and easier to maintain. Framework-driven resolution (middleware Invoke parameters, [FromServices], Minimal API parameters) is fine because it is infrastructure acting on your behalf.
I do not abstract when there is no second variant, no boundary to protect and no testing need, because an abstraction costs indirection, a name, a contract and cognitive load. Typical examples are an IOrderService with one implementation used by one controller, a generic repository over EF Core, or a wrapper around HttpClient or ILogger<T>, which are already abstractions. I do abstract at architecture boundaries (ports for payment vendors, email, storage) and where tests need a seam for something slow or non-deterministic. If an abstraction has had one implementation and one caller for a long time and is not at a boundary, I inline it.
How to tell it (STAR)
**S:** On [the policy service] our domain tests had crept from [5 seconds] to [3 minutes], and a Cosmos DB spike looked huge. **T:** I was asked to work out why the architecture wasn't protecting us. **A:** I graphed the project references and found the Domain project had picked up EF Core to use one attribute, and two handlers used `DbContext` directly. I moved all mapping to `IEntityTypeConfiguration` classes, put the handlers behind ports, and added architecture tests plus an ADR so the rule was enforced, not remembered. **R:** Domain tests went back to [6 seconds], and the Cosmos read-model change touched [4] Infrastructure files instead of [40+].
Last updated 23 Nov 2026.