O Onion Architecture
/
1TL;DR
2Origins and the Problem It Solves
3The Four Tenets
4The Layers, In Detail
5The Central Mechanic: Dependency Inversion
6Full Solution Structure and DI Wiring
7A Complete Worked Example
8Runtime Flows — Sequence Diagrams
9Change Impact: What Happens When Entities Change
10Testing Strategy Per Layer
11When To Use It — And When Not To
12Pros and Cons, Honestly
13Comparison: Layered vs Hexagonal vs Clean vs Onion vs Vertical Slice
14Common Mistakes and Anti-Patterns
15Adoption Path and ADR Template
16Reference Checklist
17Sources
Intermediate → Advanced · C# / ASP.NET Core

The Onion, peeled all
the way to the core.

A complete reference to Onion Architecture — the four tenets, every layer from Domain to Presentation, dependency inversion made concrete, runtime sequence flows, and exactly what happens to every layer when an entity changes.

17 sections 23 live diagrams 29 code samples ~55 min read
DOMAIN the core DOMAIN SERVICES APPLICATION INFRA · PRESENTATION
Scroll to begin
1

TL;DR

Onion Architecture is a way of organising an application so that all source-code dependencies point inward, toward a domain model that depends on nothing. Infrastructure — the database, the ORM, the message bus, the HTTP framework, third-party SDKs — sits on the outside, plugged in at composition time, rather than sitting underneath everything as a foundation.

The single rule that generates everything else:

Code may depend on layers more central than itself. Code may never depend on layers further out.

Three consequences fall out of that rule:

  • The domain model can be compiled, loaded and executed with no database, no web server, no framework present. That is the litmus test.
  • Swapping infrastructure (SQL Server → PostgreSQL, REST → gRPC, SMTP → SendGrid) is an additive change at the edge, not a rewrite through the middle.
  • Business rules become directly unit-testable without mocks, fixtures, or a running container.

The price you pay is indirection: more projects, more interfaces, more mapping code, and a longer path from "user clicked a button" to "row was written". Whether that price is worth paying depends almost entirely on how long the system will live and how complex its rules are — a point Palermo made explicitly in his original 2008 post, where he warned the pattern is not appropriate for small websites and is aimed at long-lived business applications with complex behaviour.


2

Origins and the Problem It Solves

2.1 The lineage

Year Pattern Author Contribution
2002 Layered Architecture (PoEAA) Martin Fowler Formalised Presentation / Domain / Data Source layering
2003 Domain-Driven Design Eric Evans Entities, Value Objects, Aggregates, Repositories, Ubiquitous Language
2005 Hexagonal / Ports & Adapters Alistair Cockburn Two rings: application inside, adapters outside; symmetry of driving/driven sides
2008 Onion Architecture Jeffrey Palermo Added internal rings to the hexagon using DDD concepts; named the pattern memorably
2012 Clean Architecture Robert C. Martin Formalised Entities / Use Cases / Interface Adapters / Frameworks; explicit use-case focus
2018 Vertical Slice Architecture Jimmy Bogard Reaction: organise by feature, not by technical layer

Onion Architecture is best understood as Ports & Adapters plus internal structure. Cockburn's hexagon says only "inside vs outside". Palermo said: the inside deserves layers too — a domain model at the dead centre, domain services around it, application services around those.

2.2 The problem with classic N-tier

In a traditional 3- or 4-tier application, dependencies flow downward, and the data-access layer is at the bottom. Everything sits on top of it.

DIAGRAM 01
flowchart TD subgraph NTIER["Classic N-Tier — dependencies flow DOWN"] direction TB A["Presentation<br/>MVC / Web API"] --> B["Business Logic Layer"] B --> C["Data Access Layer"] C --> D[("Database")] A -.-> E["Common / Utilities"] B -.-> E C -.-> E end

This looks tidy on a slide. In practice it produces four specific pathologies:

1. The database becomes the most stable thing in the system, so everything is shaped by it. Because the BLL references the DAL, the BLL's types tend to become the DAL's types. Business rules end up expressed in terms of table rows. Change the schema and the business logic changes with it — which is backwards, because the schema is an implementation detail and the business rules are the actual asset.

2. You cannot unit-test business logic without the database. Not "it's hard" — you literally cannot compile the BLL assembly without the DAL assembly, and the DAL drags in a connection string. Every "unit test" becomes an integration test, or you build an elaborate mock of an interface that was never designed to be mocked.

3. The Common project becomes a tarpit. Every layer references it, so everything eventually gets dumped there: DTOs, extension methods, enums, constants, a Helpers class, then business rules. It becomes a second, undisciplined domain layer with no rules governing it.

4. Swapping infrastructure is a rewrite. Replacing the ORM means touching every layer above it, because the ORM's types have leaked upward through the whole stack.

2.3 The fix

Onion Architecture doesn't add layers — it inverts the bottom one. Data access moves from the foundation to the outer shell, and the relationship is flipped using interfaces owned by the inside.

DIAGRAM 02
flowchart TD subgraph ONION["Onion — dependencies flow INWARD"] direction TB P["Presentation<br/>API / UI"] --> AS["Application Services"] I["Infrastructure<br/>EF Core / SMTP / HTTP clients"] --> AS AS --> DS["Domain Services"] DS --> DM["Domain Model<br/>Entities · Value Objects · Invariants"] AS --> DM I -.->|"implements interfaces defined by"| DM end

Note the arrow from Infrastructure now points inward, the same as Presentation. Conceptually the two sit at the same level in the hierarchy — both are interchangeable adapters attached to a stable core. That single inversion is the whole idea.


3

The Four Tenets

Palermo defined four tenets in 2008 and restated them unchanged four years later. Any architecture satisfying all four can legitimately be called Onion:

  1. The application is built around an independent object model. The domain model is designed from the business, not from the database schema or the API contract.

  2. Inner layers define interfaces. Outer layers implement interfaces. IOrderRepository lives in the Domain project. SqlOrderRepository lives in Infrastructure. The dependency arrow points from the implementation to the abstraction — inward.

  3. Direction of coupling is toward the centre. All coupling points inward. No exceptions, no "just this once", no #if DEBUG.

  4. All application core code can be compiled and run separate from infrastructure. This is the testable tenet. If you can't dotnet build the Core projects in a solution containing only those projects, you have violated the architecture, regardless of how the folders are named.

There's a fifth, softer rule Palermo added in part 3, which people frequently get wrong:

Any outer layer may call any inner layer directly — not just the layer immediately inside it.

Presentation is allowed to call the Domain directly. It does not have to route through an Application Service that adds nothing. This matters: forcing strict layer-by-layer traversal is a traditional layering rule, and importing it into Onion produces the pass-through-proxy problem, where you write a service method whose entire body is return _inner.DoThing();. Onion explicitly permits skipping.

Palermo also noted that an IoC container, while almost universally associated with the pattern, is not one of the tenets. Onion works fine without one; a container just makes the wiring convenient.


4

The Layers, In Detail

There is no canonical layer count. Palermo's original drawing had Domain Model → Domain Services → Application Services → outer ring. Most production .NET solutions expand this into 5–7 projects. Below is the layering I'd defend as a sensible default, from the centre out.

DIAGRAM 03
flowchart TB E["① DOMAIN MODEL<br/>Entities · Aggregates<br/>Value Objects · Enums<br/>Domain Events · Invariants<br/>Repository &amp; Port interfaces"] DSVC["② DOMAIN SERVICES<br/>Cross-entity business logic<br/>Domain event handlers<br/>Policies · Specifications"] ASVC["③ APPLICATION SERVICES<br/>Use cases / orchestration<br/>Transaction boundaries<br/>Authorisation decisions<br/>DTO ↔ Domain mapping"] PRES["④ PRESENTATION<br/>Web API · Minimal API<br/>Blazor / MVC / gRPC"] INFRA["④ INFRASTRUCTURE<br/>EF Core · Repository impls<br/>SMTP · Blob · Message bus"] TEST["TESTS<br/>Unit · Integration<br/>Architecture fitness"] E --> DSVC --> ASVC PRES --> ASVC INFRA --> ASVC TEST --> ASVC INFRA -.->|implements ports<br/>defined by| E classDef ring1 fill:#F1EEFD,stroke:#6D28D9,stroke-width:2px,color:#3B1F73 classDef ring2 fill:#E4DEFB,stroke:#6D28D9,stroke-width:1.5px,color:#3B1F73 classDef ring3 fill:#D8CFF7,stroke:#5B21B6,stroke-width:1.5px,color:#2E1856 classDef ring4 fill:#FDFCFF,stroke:#B7ACE8,stroke-width:1.3px,color:#16142A class E ring1 class DSVC ring2 class ASVC ring3 class PRES,INFRA,TEST ring4

4.1 ① Domain Model — the core

Depends on: nothing. Not EF Core. Not Microsoft.Extensions.*. Not Newtonsoft.Json. Ideally not even System.Text.Json attributes. The .csproj should have zero PackageReference entries beyond, at most, a nullable-annotation helper.

Contains:

Artefact Purpose
Entities Objects with identity and a lifecycle. Order, Customer, Invoice.
Aggregates & Aggregate Roots Consistency boundaries. Only the root is externally addressable; the root enforces invariants over its members.
Value Objects Immutable, identity-free, compared by value. Money, EmailAddress, DateRange, Sku.
Domain Events Facts about something that already happened. OrderPlaced, PaymentCaptured.
Invariants Rules that must hold at every observable moment. Enforced in constructors and methods, not by external validators.
Repository interfaces IOrderRepository. One per aggregate root, not one per table.
Port interfaces IClock, IPaymentGateway, IExchangeRateProvider — anything the domain needs but cannot itself provide.
Domain exceptions InsufficientStockException. Business failures, not SqlException.
Specifications Reusable, composable predicates over the model.

The defining test: you could take this project, drop it into a console app with no other references, new up an aggregate, call its methods, and observe correct business behaviour. If you can't, something has leaked in.

What must NOT be here: [Table]/[Column] attributes, DbSet<T>, IQueryable<T> in interface signatures, HttpContext, connection strings, ILogger<T> sprinkled through entities, or DTOs.

On IQueryable<T>: returning IQueryable<T> from a repository interface is one of the most common silent violations. It looks framework-free — IQueryable lives in System.Linq — but it hands the caller a lazily-composed expression tree whose translation semantics belong to the ORM. The caller now depends on which LINQ operators your provider supports. Return materialised aggregates or a Specification, not a query.

4.2 ② Domain Services

Depends on: Domain Model only.

Domain Services exist for business logic that doesn't naturally belong to a single entity. The classic signal: you have a rule involving two or more aggregates, and putting it on either one would be arbitrary or would require that aggregate to load the other.

Examples that belong here: - TransferService.Transfer(Account from, Account to, Money amount) — the rule spans two aggregates. - PricingService.CalculatePrice(Order order, DiscountPolicy policy, TaxRegime regime) — needs several domain concepts, owned by none. - Domain event handlers that trigger further domain behaviour.

Examples that do not belong here: - Anything that starts a transaction (that's Application). - Anything that reads from a repository just to hydrate one thing and mutate it (usually that's an Application Service, or the logic belongs on the aggregate). - OrderService.CreateOrder() that is really just an orchestration wrapper — that's an Application Service wearing the wrong badge.

Domain Services are stateless, take domain types in, return domain types out, and are named after business activities, not CRUD verbs.

Many teams collapse this layer into the Domain Model project as a Services/ folder. That's fine and common — the logical layer matters more than the project count.

4.3 ③ Application Services

Depends on: Domain Services, Domain Model.

This is the use-case layer. One method (or one handler class) per thing a user or system can do. It is the layer that answers "what does this application actually offer?"

Responsibilities:

  • Orchestration — load aggregate(s) via repository interfaces, invoke domain behaviour, persist via Unit of Work.
  • Transaction boundary — a use case is typically one transaction. This is the only layer that should know that.
  • Authorisation — "may this user do this?" is application policy, not domain invariant.
  • DTO ↔ Domain translation — the domain model never crosses the process boundary.
  • Cross-cutting orchestration — logging, caching decisions, retry policy selection, publishing integration events.

Anti-responsibilities: business rules. If you find an if (order.Total > 10_000) in an Application Service, that rule belongs on Order.

A structural note. Many teams split this into three projects (as Code Maze's reference solution does):

Project Contains References
App.Domain entities, VOs, repository interfaces —
App.Contracts DTOs, request/response records App.Domain (or nothing)
App.Services.Abstractions IOrderService etc. App.Contracts, App.Domain
App.Services OrderService etc. all three above

The reason for the split is precise: Presentation should reference Services.Abstractions and Contracts, but NOT Services. That physically prevents a controller from new-ing a concrete service or reaching into implementation internals. The only place App.Services is referenced is the composition root. It's a real constraint, enforced by the compiler, and it costs you two extra .csproj files.

If you'd rather not, one App.Application project with folders works — you just lose that compile-time guarantee.

4.4 ④ Infrastructure

Depends on: the Core layers. Depended upon by: the composition root only.

Everything that talks to the outside world:

  • Persistence — DbContext, IEntityTypeConfiguration<T> classes, migrations, repository implementations, Unit of Work implementation.
  • Integration — HTTP clients for third-party APIs, message bus publishers/consumers, file/blob storage.
  • System services — SystemClock : IClock, Guid-based ID generators, email senders, PDF renderers.
  • Cross-cutting implementations — distributed cache, feature flag provider, secret store.

Common sub-split: App.Persistence (EF Core, DB-only) and App.Infrastructure (everything else). Useful because persistence has migrations and a very different test story from an HTTP adapter.

This is where the ORM lives, and it lives here alone. If Microsoft.EntityFrameworkCore appears as a PackageReference in any Core project, the architecture is broken. (The one contested exception: some teams put DbContext interfaces or IUnitOfWork in Core — that's fine as long as the interface exposes no EF types.)

4.5 ④ Presentation

Depends on: Application Services abstractions + Contracts.

Controllers, minimal-API endpoint groups, Blazor components, gRPC services, GraphQL resolvers, hosted background services, CLI commands. Also: model binding, HTTP status code selection, content negotiation, API versioning, OpenAPI metadata.

A controller action in a healthy Onion solution is typically 3–6 lines: bind, delegate, map result to status code. If it's 40 lines, logic has leaked outward.

Note that Presentation and Infrastructure sit at the same conceptual level. Neither depends on the other. Both are adapters. A Blazor UI and a SQL Server database are, architecturally, the same kind of thing: replaceable edges.

4.6 Cross-cutting concerns

Onion has no dedicated ring for logging, validation, caching, and error handling, and this trips people up. The resolution:

Concern Where the abstraction lives Where the implementation lives
Logging ILogger<T> from Microsoft.Extensions.Logging.Abstractions — acceptable in Application; keep out of Domain Composition root (Serilog, OTel)
Validation — invariants Domain (constructors, methods, throw) Domain
Validation — input shape Application (FluentValidation) or Presentation same
Caching Port interface in Application Infrastructure
Transactions IUnitOfWork interface in Domain/Application Infrastructure (DbContext.SaveChangesAsync)
Authentication Presentation (middleware) Presentation / Infrastructure
Authorisation Application (policy decision) Application, with data from Infrastructure
Time IClock in Domain Infrastructure (TimeProvider-backed)

The recurring pattern is: interface inward, implementation outward. When a cross-cutting concern doesn't fit that shape, it usually means it's actually a pipeline concern — use middleware, MediatR pipeline behaviours, or DI decorators at the composition root.

4.7 The composition root

There is exactly one place in the whole system that is allowed to know every concrete type: Program.cs in the host project. It references all projects, wires interfaces to implementations, and is the only file where the architecture's rules are deliberately suspended.

This creates a mild irregularity — the Presentation project's .csproj ends up referencing Infrastructure, which looks like a violation. Two ways to handle it:

  1. Accept it. Add an architecture test asserting that no type in the Presentation namespace depends on Infrastructure types, even though the assembly reference exists. This is the pragmatic default.
  2. Extract a separate App.Bootstrapper host project that references everything, with the API project as a library. Cleaner, one more project.

5

The Central Mechanic: Dependency Inversion

Everything above rests on one trick. It's worth seeing it isolated.

DIAGRAM 04
flowchart LR subgraph BEFORE["N-Tier: coupling flows toward the database"] direction LR B1["OrderService"] -->|"depends on concrete"| B2["OrderRepository"] B2 --> B3[("SQL Server")] end
DIAGRAM 05
flowchart RL subgraph AFTER["Onion: coupling flows toward the domain"] direction RL A2["SqlOrderRepository<br/><i>Infrastructure</i>"] -.->|"implements"| A1["IOrderRepository<br/><i>Domain</i>"] A3["PlaceOrderHandler<br/><i>Application</i>"] -->|"depends on abstraction"| A1 A2 --> A4[("SQL Server")] A5["Composition Root"] -->|"binds at startup"| A2 end

The interface IOrderRepository is defined by the consumer, not the provider. This is the part people miss. It is not "the data layer publishes an interface so we can mock it". It is "the domain declares what it needs, and someone outside is obliged to satisfy that contract". Ownership of the contract sits with the inside.

Practical consequence: IOrderRepository should have methods the domain use cases need — Task<Order?> FindByIdAsync(OrderId id), Task<Order?> FindPendingForCustomerAsync(CustomerId id) — not methods the database finds convenient — IQueryable<Order> Query(), Task<List<Order>> GetAllAsync().

At runtime, control flows outward (Application calls the repository implementation), while at compile time, dependency points inward. That inversion of the two directions is what the Dependency Inversion Principle buys you, and it is the entire structural basis of the pattern.


6

Full Solution Structure and DI Wiring

6.1 Directory layout

Text
OnionShop/
├── Directory.Build.props              # shared TFM, nullable, langversion, analyzers
├── Directory.Packages.props           # central package management (CPM)
├── OnionShop.sln
│
├── src/
│   ├── Core/
│   │   ├── OnionShop.Domain/                     ← ① no package references
│   │   │   ├── Common/
│   │   │   │   ├── Entity.cs
│   │   │   │   ├── AggregateRoot.cs
│   │   │   │   ├── ValueObject.cs
│   │   │   │   ├── IDomainEvent.cs
│   │   │   │   └── Result.cs
│   │   │   ├── Orders/
│   │   │   │   ├── Order.cs                      ← aggregate root
│   │   │   │   ├── OrderLine.cs                  ← aggregate member
│   │   │   │   ├── OrderId.cs                    ← strongly-typed ID
│   │   │   │   ├── OrderStatus.cs
│   │   │   │   ├── Events/OrderPlaced.cs
│   │   │   │   └── IOrderRepository.cs           ← port, owned by domain
│   │   │   ├── Customers/
│   │   │   ├── SharedKernel/
│   │   │   │   ├── Money.cs
│   │   │   │   ├── Sku.cs
│   │   │   │   └── EmailAddress.cs
│   │   │   ├── Services/                         ← ② domain services
│   │   │   │   └── IPricingService.cs / PricingService.cs
│   │   │   ├── Abstractions/
│   │   │   │   ├── IUnitOfWork.cs
│   │   │   │   └── IClock.cs
│   │   │   └── Exceptions/
│   │   │       └── DomainException.cs
│   │   │
│   │   ├── OnionShop.Contracts/                  ← DTOs only
│   │   │   └── Orders/
│   │   │       ├── PlaceOrderRequest.cs
│   │   │       ├── OrderDto.cs
│   │   │       └── OrderLineDto.cs
│   │   │
│   │   ├── OnionShop.Application.Abstractions/   ← ③ service interfaces
│   │   │   └── Orders/IOrderService.cs
│   │   │
│   │   └── OnionShop.Application/                ← ③ use case implementations
│   │       ├── Orders/OrderService.cs
│   │       ├── Orders/OrderMapper.cs
│   │       ├── Behaviours/                       ← if using MediatR pipeline
│   │       └── DependencyInjection.cs
│   │
│   ├── Infrastructure/
│   │   ├── OnionShop.Persistence/                ← ④ EF Core only
│   │   │   ├── ShopDbContext.cs
│   │   │   ├── Configurations/OrderConfiguration.cs
│   │   │   ├── Repositories/OrderRepository.cs
│   │   │   ├── UnitOfWork.cs
│   │   │   ├── Interceptors/DomainEventInterceptor.cs
│   │   │   ├── Migrations/
│   │   │   └── DependencyInjection.cs
│   │   │
│   │   └── OnionShop.Infrastructure/             ← ④ everything else external
│   │       ├── Email/SmtpEmailSender.cs
│   │       ├── Payments/StripePaymentGateway.cs
│   │       ├── Time/SystemClock.cs
│   │       └── DependencyInjection.cs
│   │
│   └── Presentation/
│       └── OnionShop.Api/                        ← ④ + composition root
│           ├── Program.cs
│           ├── Endpoints/OrderEndpoints.cs
│           ├── Middleware/ExceptionHandler.cs
│           └── appsettings.json
│
└── tests/
    ├── OnionShop.Domain.UnitTests/
    ├── OnionShop.Application.UnitTests/
    ├── OnionShop.Persistence.IntegrationTests/
    ├── OnionShop.Api.FunctionalTests/
    └── OnionShop.ArchitectureTests/               ← fitness functions

6.2 Project reference matrix

This table is the architecture. Everything else is convention; this is enforced by the compiler.

Project Layer References
Domain ① ② Core (none)
Contracts Core Domain (or nothing, if DTOs are primitive-only)
Application.Abstractions ③ Core Domain, Contracts
Application ③ Core Domain, Contracts, Application.Abstractions
Persistence ④ Infra Domain (only!)
Infrastructure ④ Infra Domain, Application.Abstractions
Api ④ Pres Application.Abstractions, Contracts — plus Application, Persistence, Infrastructure for composition only
ArchitectureTests Test everything
DIAGRAM 06
flowchart RL API["OnionShop.Api"] --> AA["Application.Abstractions"] API --> CON["Contracts"] API -. "composition root only" .-> APP["Application"] API -. "composition root only" .-> PER["Persistence"] API -. "composition root only" .-> INF["Infrastructure"] PER --> DOM["Domain"] INF --> DOM INF --> AA APP --> AA APP --> CON APP --> DOM AA --> CON AA --> DOM CON --> DOM

Read the arrows. Every solid arrow terminates at something more central. There is no path from Domain to anything. That's the invariant.

6.3 Locking it down in the .csproj

The Domain project should be actively hostile to dependencies:

XML
<!-- src/Core/OnionShop.Domain/OnionShop.Domain.csproj -->
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <LangVersion>latest</LangVersion>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <!-- Fail the build if anyone adds a transitive package here -->
    <NoWarn></NoWarn>
  </PropertyGroup>
  <!-- Deliberately empty: no ProjectReference, no PackageReference. -->
</Project>

6.4 Modular DI registration

Each layer owns its own registration extension. The composition root calls them in order and never sees a concrete type from the inner layers.

C#
// src/Core/OnionShop.Application/DependencyInjection.cs
namespace OnionShop.Application;

public static class DependencyInjection
{
    public static IServiceCollection AddApplication(this IServiceCollection services)
    {
        services.AddScoped<IOrderService, OrderService>();
        services.AddScoped<IPricingService, PricingService>();   // domain service
        services.AddValidatorsFromAssemblyContaining<PlaceOrderRequestValidator>();
        return services;
    }
}
C#
// src/Infrastructure/OnionShop.Persistence/DependencyInjection.cs
namespace OnionShop.Persistence;

public static class DependencyInjection
{
    public static IServiceCollection AddPersistence(
        this IServiceCollection services, IConfiguration config)
    {
        services.AddDbContext<ShopDbContext>((sp, options) =>
            options.UseSqlServer(config.GetConnectionString("Shop"),
                    sql => sql.EnableRetryOnFailure())
                   .AddInterceptors(sp.GetRequiredService<DomainEventInterceptor>()));

        services.AddScoped<DomainEventInterceptor>();
        services.AddScoped<IOrderRepository, OrderRepository>();
        services.AddScoped<ICustomerRepository, CustomerRepository>();
        services.AddScoped<IUnitOfWork>(sp => sp.GetRequiredService<ShopDbContext>());
        return services;
    }
}
C#
// src/Infrastructure/OnionShop.Infrastructure/DependencyInjection.cs
public static IServiceCollection AddInfrastructure(
    this IServiceCollection services, IConfiguration config)
{
    services.AddSingleton(TimeProvider.System);
    services.AddSingleton<IClock, SystemClock>();
    services.AddScoped<IEmailSender, SmtpEmailSender>();
    services.AddHttpClient<IPaymentGateway, StripePaymentGateway>(c =>
        c.BaseAddress = new Uri(config["Stripe:BaseUrl"]!))
        .AddStandardResilienceHandler();
    return services;
}
C#
// src/Presentation/OnionShop.Api/Program.cs  — THE composition root
var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddApplication()                                  // ③
    .AddPersistence(builder.Configuration)             // ④
    .AddInfrastructure(builder.Configuration);         // ④

builder.Services.AddOpenApi();
builder.Services.AddProblemDetails();
builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddAuthorization();

var app = builder.Build();

app.UseExceptionHandler();          // maps DomainException → ProblemDetails
app.MapOpenApi();
app.UseAuthentication();
app.UseAuthorization();
app.MapOrderEndpoints();            // ④ Presentation

app.Run();

public partial class Program;       // for WebApplicationFactory in tests

This is the only file in the solution that references a concrete implementation type. Every other file talks to interfaces owned by inner layers. If you can say that honestly about your solution, you are doing Onion Architecture; if you can't, you're doing folder-shaped N-tier.


7

A Complete Worked Example

Domain: a shop where a customer places an order. Business rules:

  • An order must have at least one line.
  • All lines must be in the same currency as the order.
  • An order over £10,000 requires manual approval and cannot be confirmed directly.
  • Once confirmed, lines cannot be added or removed.
  • Quantity must be positive; unit price must be non-negative.

Watch where each rule ends up.

7.1 ① Domain — building blocks

C#
// Domain/Common/Entity.cs
namespace OnionShop.Domain.Common;

public abstract class Entity<TId> where TId : notnull
{
    public TId Id { get; protected set; } = default!;

    public override bool Equals(object? obj) =>
        obj is Entity<TId> other && GetType() == other.GetType()
        && EqualityComparer<TId>.Default.Equals(Id, other.Id);

    public override int GetHashCode() => HashCode.Combine(GetType(), Id);
}

// Domain/Common/AggregateRoot.cs
public abstract class AggregateRoot<TId>(TId id) : Entity<TId> where TId : notnull
{
    private readonly List<IDomainEvent> _domainEvents = [];
    public IReadOnlyCollection<IDomainEvent> DomainEvents => _domainEvents.AsReadOnly();

    protected AggregateRoot() : this(default!) { }   // EF Core materialisation

    protected void Raise(IDomainEvent e) => _domainEvents.Add(e);
    public void ClearDomainEvents() => _domainEvents.Clear();
}

// Domain/Common/IDomainEvent.cs
public interface IDomainEvent
{
    DateTimeOffset OccurredOn { get; }
}
C#
// Domain/SharedKernel/Money.cs — a value object
namespace OnionShop.Domain.SharedKernel;

public readonly record struct Money
{
    public decimal Amount { get; }
    public string Currency { get; }

    public Money(decimal amount, string currency)
    {
        if (string.IsNullOrWhiteSpace(currency) || currency.Length != 3)
            throw new DomainException("Currency must be a 3-letter ISO code.");
        if (decimal.Round(amount, 2) != amount)
            throw new DomainException("Money supports at most 2 decimal places.");

        Amount = amount;
        Currency = currency.ToUpperInvariant();
    }

    public static Money Zero(string currency) => new(0m, currency);

    public static Money operator +(Money a, Money b)
    {
        EnsureSameCurrency(a, b);
        return new Money(a.Amount + b.Amount, a.Currency);
    }

    public static Money operator *(Money m, int qty) => new(m.Amount * qty, m.Currency);

    public static bool operator >(Money a, Money b) { EnsureSameCurrency(a, b); return a.Amount > b.Amount; }
    public static bool operator <(Money a, Money b) { EnsureSameCurrency(a, b); return a.Amount < b.Amount; }

    private static void EnsureSameCurrency(Money a, Money b)
    {
        if (a.Currency != b.Currency)
            throw new DomainException($"Currency mismatch: {a.Currency} vs {b.Currency}.");
    }

    public override string ToString() => $"{Amount:0.00} {Currency}";
}
C#
// Domain/Orders/OrderId.cs — strongly-typed identity
public readonly record struct OrderId(Guid Value)
{
    public static OrderId New() => new(Guid.CreateVersion7());
    public override string ToString() => Value.ToString();
}

7.2 ① Domain — the aggregate root

This is where the business rules live. Note: no attributes, no framework types, no public setters, no public collection.

C#
// Domain/Orders/Order.cs
namespace OnionShop.Domain.Orders;

public sealed class Order : AggregateRoot<OrderId>
{
    public const decimal ManualApprovalThreshold = 10_000m;

    private readonly List<OrderLine> _lines = [];

    public CustomerId CustomerId { get; private set; }
    public string Currency { get; private set; } = null!;
    public OrderStatus Status { get; private set; }
    public DateTimeOffset PlacedOn { get; private set; }

    public IReadOnlyList<OrderLine> Lines => _lines.AsReadOnly();

    public Money Total => _lines.Aggregate(
        Money.Zero(Currency), (acc, l) => acc + l.LineTotal);

    public bool RequiresManualApproval => Total.Amount > ManualApprovalThreshold;

    private Order() { }                                    // EF Core only

    private Order(OrderId id, CustomerId customerId, string currency, DateTimeOffset placedOn)
        : base(id)
    {
        CustomerId = customerId;
        Currency = currency;
        Status = OrderStatus.Draft;
        PlacedOn = placedOn;
    }

    /// <summary>Factory. The ONLY way an Order comes into existence.</summary>
    public static Order Place(CustomerId customerId, string currency, IClock clock)
    {
        var order = new Order(OrderId.New(), customerId, currency, clock.UtcNow);
        order.Raise(new OrderPlaced(order.Id, customerId, clock.UtcNow));
        return order;
    }

    public void AddLine(Sku sku, int quantity, Money unitPrice)
    {
        EnsureMutable();

        if (quantity <= 0)
            throw new DomainException("Quantity must be positive.");
        if (unitPrice.Currency != Currency)
            throw new DomainException(
                $"Line currency {unitPrice.Currency} does not match order currency {Currency}.");

        var existing = _lines.SingleOrDefault(l => l.Sku == sku);
        if (existing is not null) existing.IncreaseQuantity(quantity);
        else _lines.Add(OrderLine.For(Id, sku, quantity, unitPrice));
    }

    public void RemoveLine(Sku sku)
    {
        EnsureMutable();
        var line = _lines.SingleOrDefault(l => l.Sku == sku)
            ?? throw new DomainException($"SKU {sku} is not on this order.");
        _lines.Remove(line);
    }

    public void Confirm(IClock clock)
    {
        EnsureMutable();

        if (_lines.Count == 0)
            throw new DomainException("An order must have at least one line.");
        if (RequiresManualApproval)
            throw new DomainException(
                $"Orders above {ManualApprovalThreshold:0.00} {Currency} require manual approval.");

        Status = OrderStatus.Confirmed;
        Raise(new OrderConfirmed(Id, CustomerId, Total, clock.UtcNow));
    }

    private void EnsureMutable()
    {
        if (Status is not OrderStatus.Draft)
            throw new DomainException($"Order in status {Status} can no longer be modified.");
    }
}
C#
// Domain/Orders/OrderLine.cs — aggregate member, not a root
public sealed class OrderLine : Entity<Guid>
{
    public OrderId OrderId { get; private set; }
    public Sku Sku { get; private set; }
    public int Quantity { get; private set; }
    public Money UnitPrice { get; private set; }

    public Money LineTotal => UnitPrice * Quantity;

    private OrderLine() { }

    internal static OrderLine For(OrderId orderId, Sku sku, int qty, Money unitPrice) =>
        new() { Id = Guid.CreateVersion7(), OrderId = orderId,
                Sku = sku, Quantity = qty, UnitPrice = unitPrice };

    internal void IncreaseQuantity(int by)
    {
        if (by <= 0) throw new DomainException("Increase must be positive.");
        Quantity += by;
    }
}

Note internal on the mutators: nothing outside the Domain assembly can call them. The aggregate root is the only door.

7.3 ① Domain — the ports

C#
// Domain/Orders/IOrderRepository.cs
public interface IOrderRepository
{
    Task<Order?> FindAsync(OrderId id, CancellationToken ct = default);
    Task<IReadOnlyList<Order>> FindDraftsForCustomerAsync(CustomerId id, CancellationToken ct = default);
    void Add(Order order);
    void Remove(Order order);
}

// Domain/Abstractions/IUnitOfWork.cs
public interface IUnitOfWork
{
    Task<int> SaveChangesAsync(CancellationToken ct = default);
}

// Domain/Abstractions/IClock.cs
public interface IClock { DateTimeOffset UtcNow { get; } }

Look at what's not here: no GetAll(), no IQueryable, no Update() (EF change tracking handles that; making it explicit would be a leak of persistence semantics into the domain — though some teams add it deliberately for ORM-agnosticism, which is a defensible trade).

7.4 ③ Application — the use case

C#
// Contracts/Orders/PlaceOrderRequest.cs
public sealed record PlaceOrderRequest(
    Guid CustomerId,
    string Currency,
    IReadOnlyList<PlaceOrderLine> Lines);

public sealed record PlaceOrderLine(string Sku, int Quantity, decimal UnitPrice);

// Contracts/Orders/OrderDto.cs
public sealed record OrderDto(
    Guid Id, Guid CustomerId, string Status, string Currency,
    decimal Total, DateTimeOffset PlacedOn, IReadOnlyList<OrderLineDto> Lines);

public sealed record OrderLineDto(string Sku, int Quantity, decimal UnitPrice, decimal LineTotal);
C#
// Application.Abstractions/Orders/IOrderService.cs
public interface IOrderService
{
    Task<OrderDto> PlaceAsync(PlaceOrderRequest request, CancellationToken ct = default);
    Task<OrderDto?> GetAsync(Guid orderId, CancellationToken ct = default);
}
C#
// Application/Orders/OrderService.cs
internal sealed class OrderService(
    IOrderRepository orders,
    ICustomerRepository customers,
    IUnitOfWork unitOfWork,
    IClock clock,
    ILogger<OrderService> logger) : IOrderService
{
    public async Task<OrderDto> PlaceAsync(PlaceOrderRequest request, CancellationToken ct = default)
    {
        // 1. Application concern: does the referenced actor exist?
        var customerId = new CustomerId(request.CustomerId);
        if (!await customers.ExistsAsync(customerId, ct))
            throw new NotFoundException($"Customer {customerId} not found.");

        // 2. Delegate ALL business rules to the domain.
        var order = Order.Place(customerId, request.Currency, clock);

        foreach (var line in request.Lines)
            order.AddLine(new Sku(line.Sku), line.Quantity,
                          new Money(line.UnitPrice, request.Currency));

        order.Confirm(clock);

        // 3. Application concern: persistence + transaction boundary.
        orders.Add(order);
        await unitOfWork.SaveChangesAsync(ct);

        logger.LogInformation("Order {OrderId} placed for {CustomerId}", order.Id, customerId);

        // 4. Application concern: translate to the outside world's shape.
        return order.ToDto();
    }

    public async Task<OrderDto?> GetAsync(Guid orderId, CancellationToken ct = default) =>
        (await orders.FindAsync(new OrderId(orderId), ct))?.ToDto();
}

The service is thin and boring. Every if in it is about this application, not about orders in general. That's the tell that the split is correct.

C#
// Application/Orders/OrderMapper.cs
internal static class OrderMapper
{
    public static OrderDto ToDto(this Order o) => new(
        o.Id.Value, o.CustomerId.Value, o.Status.ToString(), o.Currency,
        o.Total.Amount, o.PlacedOn,
        [.. o.Lines.Select(l => new OrderLineDto(
            l.Sku.Value, l.Quantity, l.UnitPrice.Amount, l.LineTotal.Amount))]);
}

7.5 ④ Persistence — the adapter

C#
// Persistence/Configurations/OrderConfiguration.cs
internal sealed class OrderConfiguration : IEntityTypeConfiguration<Order>
{
    public void Configure(EntityTypeBuilder<Order> b)
    {
        b.ToTable("Orders");

        b.HasKey(o => o.Id);
        b.Property(o => o.Id)
            .HasConversion(id => id.Value, value => new OrderId(value))
            .ValueGeneratedNever();

        b.Property(o => o.CustomerId)
            .HasConversion(id => id.Value, value => new CustomerId(value));

        b.Property(o => o.Currency).HasMaxLength(3).IsRequired();
        b.Property(o => o.Status).HasConversion<string>().HasMaxLength(32);
        b.Property(o => o.PlacedOn);

        // Map the private backing field, not the public read-only projection.
        b.OwnsMany(o => o.Lines, lb =>
        {
            lb.ToTable("OrderLines");
            lb.WithOwner().HasForeignKey(l => l.OrderId);
            lb.HasKey(l => l.Id);
            lb.Property(l => l.Sku)
              .HasConversion(s => s.Value, v => new Sku(v)).HasMaxLength(32);
            lb.Property(l => l.Quantity);
            lb.OwnsOne(l => l.UnitPrice, mb =>
            {
                mb.Property(m => m.Amount).HasColumnName("UnitPriceAmount").HasPrecision(18, 2);
                mb.Property(m => m.Currency).HasColumnName("UnitPriceCurrency").HasMaxLength(3);
            });
        });
        b.Navigation(o => o.Lines).UsePropertyAccessMode(PropertyAccessMode.Field);

        b.Ignore(o => o.Total);                 // computed in the domain
        b.Ignore(o => o.RequiresManualApproval);
        b.Ignore(o => o.DomainEvents);
    }
}

This file is the pressure valve of the whole architecture. The domain got to be shaped by the business — private setters, value objects, no attributes — because this configuration class absorbs all the impedance mismatch. Every constraint EF Core would otherwise have imposed on Order.cs lives here instead.

C#
// Persistence/Repositories/OrderRepository.cs
internal sealed class OrderRepository(ShopDbContext db) : IOrderRepository
{
    public Task<Order?> FindAsync(OrderId id, CancellationToken ct = default) =>
        db.Orders.FirstOrDefaultAsync(o => o.Id == id, ct);

    public async Task<IReadOnlyList<Order>> FindDraftsForCustomerAsync(
        CustomerId id, CancellationToken ct = default) =>
        await db.Orders
            .Where(o => o.CustomerId == id && o.Status == OrderStatus.Draft)
            .ToListAsync(ct);

    public void Add(Order order) => db.Orders.Add(order);
    public void Remove(Order order) => db.Orders.Remove(order);
}

// Persistence/ShopDbContext.cs
public sealed class ShopDbContext(DbContextOptions<ShopDbContext> options)
    : DbContext(options), IUnitOfWork
{
    internal DbSet<Order> Orders => Set<Order>();
    internal DbSet<Customer> Customers => Set<Customer>();

    protected override void OnModelCreating(ModelBuilder mb) =>
        mb.ApplyConfigurationsFromAssembly(typeof(ShopDbContext).Assembly);
}

Note ShopDbContext : IUnitOfWork — the Application layer receives IUnitOfWork and never learns that SaveChangesAsync belongs to EF Core.

7.6 ④ Presentation — the other adapter

C#
// Api/Endpoints/OrderEndpoints.cs
public static class OrderEndpoints
{
    public static IEndpointRouteBuilder MapOrderEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/api/v1/orders").WithTags("Orders").RequireAuthorization();

        group.MapPost("/", async (
                PlaceOrderRequest request,
                IOrderService service,
                CancellationToken ct) =>
            {
                var dto = await service.PlaceAsync(request, ct);
                return Results.Created($"/api/v1/orders/{dto.Id}", dto);
            })
            .WithName("PlaceOrder")
            .Produces<OrderDto>(StatusCodes.Status201Created)
            .ProducesProblem(StatusCodes.Status400BadRequest);

        group.MapGet("/{id:guid}", async (
                Guid id, IOrderService service, CancellationToken ct) =>
            await service.GetAsync(id, ct) is { } dto ? Results.Ok(dto) : Results.NotFound())
            .WithName("GetOrder");

        return app;
    }
}

Three lines of logic per endpoint. Domain exceptions are translated to ProblemDetails centrally:

C#
// Api/Middleware/DomainExceptionHandler.cs
internal sealed class DomainExceptionHandler : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(
        HttpContext ctx, Exception ex, CancellationToken ct)
    {
        var (status, title) = ex switch
        {
            DomainException   => (StatusCodes.Status400BadRequest, "Business rule violated"),
            NotFoundException => (StatusCodes.Status404NotFound,   "Resource not found"),
            _                 => (0, "")
        };
        if (status == 0) return false;

        await ctx.Response.WriteAsJsonAsync(new ProblemDetails
        {
            Status = status, Title = title, Detail = ex.Message,
            Instance = ctx.Request.Path
        }, ct);
        return true;
    }
}

8

Runtime Flows — Sequence Diagrams

8.1 Write flow: POST /api/v1/orders

DIAGRAM 07
sequenceDiagram autonumber actor Client participant EP as ④ Endpoint<br/>Presentation participant SVC as ③ OrderService<br/>Application participant REPO as ④ OrderRepository<br/>Persistence participant AGG as ① Order aggregate<br/>Domain participant UOW as ④ ShopDbContext<br/>IUnitOfWork participant DB as SQL Server Client->>EP: POST /orders {customerId, lines[]} EP->>EP: model binding + auth EP->>SVC: PlaceAsync(request, ct) SVC->>REPO: customers.ExistsAsync(customerId) REPO->>DB: SELECT 1 FROM Customers WHERE Id=@p0 DB-->>REPO: true REPO-->>SVC: true Note over SVC,AGG: All business rules execute here — in memory, no I/O SVC->>AGG: Order.Place(customerId, currency, clock) AGG->>AGG: raise OrderPlaced AGG-->>SVC: order loop for each requested line SVC->>AGG: AddLine(sku, qty, unitPrice) AGG->>AGG: EnsureMutable · validate qty · validate currency end SVC->>AGG: Confirm(clock) AGG->>AGG: check ≥1 line · check approval threshold AGG->>AGG: Status = Confirmed · raise OrderConfirmed AGG-->>SVC: ok SVC->>REPO: orders.Add(order) REPO->>REPO: db.Orders.Add(order) — change tracker only SVC->>UOW: SaveChangesAsync(ct) UOW->>UOW: interceptor collects DomainEvents UOW->>DB: BEGIN TRAN · INSERT Orders · INSERT OrderLines · COMMIT DB-->>UOW: 3 rows UOW-->>SVC: 3 SVC->>SVC: order.ToDto() SVC-->>EP: OrderDto EP-->>Client: 201 Created + Location + body

Two things to notice:

  • Steps 8–18 involve no I/O whatsoever. The entire business decision is made against in-memory objects. That's why these rules are unit-testable in microseconds.
  • The only transaction boundary is step 22, owned by the Application layer via an interface it defined. Neither Domain nor Presentation knows a transaction exists.

8.2 Failure flow: a business rule rejects the request

DIAGRAM 08
sequenceDiagram autonumber actor Client participant EP as ④ Endpoint participant MW as ④ ExceptionHandler participant SVC as ③ OrderService participant AGG as ① Order participant DB as SQL Server Client->>EP: POST /orders (total £14,000) EP->>SVC: PlaceAsync(request) SVC->>AGG: Order.Place(...) then AddLine(...) ×n SVC->>AGG: Confirm(clock) AGG->>AGG: RequiresManualApproval == true AGG--xSVC: throw DomainException Note over SVC,DB: SaveChangesAsync is never reached.<br/>Nothing was written. No compensation needed. SVC--xEP: DomainException propagates EP->>MW: unhandled exception MW->>MW: map DomainException → 400 ProblemDetails MW-->>Client: 400 {title: "Business rule violated", detail: "..."}

The valuable property here: because the aggregate refuses to enter an invalid state before persistence is touched, there is no partial write and no rollback logic to get wrong. Invariants enforced at the centre make the outer layers simpler.

8.3 Read flow, and why it often deserves a different path

DIAGRAM 09
sequenceDiagram autonumber actor Client participant EP as ④ Endpoint participant SVC as ③ OrderService participant REPO as ④ Repository participant DB as SQL Server Client->>EP: GET /orders/{id} EP->>SVC: GetAsync(id) SVC->>REPO: FindAsync(OrderId) REPO->>DB: SELECT ... FROM Orders JOIN OrderLines DB-->>REPO: rows REPO->>REPO: EF materialises full Order aggregate REPO-->>SVC: Order (fully hydrated, change-tracked) SVC->>SVC: ToDto() — flatten SVC-->>EP: OrderDto EP-->>Client: 200 OK

Steps 6–8 are pure waste for a read. You hydrated an aggregate with all its invariant-enforcing machinery, attached it to the change tracker, and then immediately flattened it to a DTO you could have projected directly in SQL.

This is the single most common performance complaint about Onion, and the standard answer is CQRS-lite: keep the write side going through the aggregate, and let the read side bypass it.

DIAGRAM 10
flowchart LR subgraph WRITE["Write side — full Onion"] W1["Endpoint"] --> W2["Command handler"] --> W3["Aggregate<br/>invariants"] --> W4["Repository"] --> W5[("DB")] end subgraph READ["Read side — thin"] R1["Endpoint"] --> R2["Query handler"] --> R3["Projection / Dapper /<br/>EF .Select() to DTO"] --> R5[("DB / read replica")] end

Is bypassing the domain on reads a violation? No — recall tenet-adjacent rule that any outer layer may call any inner layer directly, and note that a read performs no state transition, so there are no invariants to protect. What you must keep is: reads never mutate, and query DTOs are never fed back into a write path without going through the aggregate. Many teams put query handlers in Application with a IReadOnlyOrderQueries port implemented in Persistence — that keeps the dependency arrow pointing inward while skipping the aggregate.

8.4 Domain events crossing the boundary

Domain events are raised inside the aggregate (which knows nothing about dispatch) and dispatched by infrastructure at the transaction boundary.

DIAGRAM 11
sequenceDiagram autonumber participant AGG as ① Order participant UOW as ④ ShopDbContext participant INT as ④ DomainEventInterceptor participant DISP as ③ Dispatcher participant H as ② / ③ Handlers participant OUT as ④ Outbox table AGG->>AGG: Raise(OrderConfirmed) Note over AGG: event sits in _domainEvents<br/>Domain has zero knowledge of dispatch UOW->>INT: SavingChangesAsync INT->>UOW: scan ChangeTracker for AggregateRoot INT->>UOW: collect + ClearDomainEvents() alt in-process handling INT->>DISP: Publish(events) DISP->>H: OrderConfirmedHandler.Handle(e) H->>H: domain reaction (e.g. reserve stock) else reliable integration INT->>OUT: INSERT OutboxMessages (same transaction) Note over OUT: background dispatcher publishes<br/>to the bus after commit end UOW->>UOW: COMMIT

The key architectural point: Order raises OrderConfirmed as a plain record with no base class from any framework. The ability to react is added entirely from outside. The domain stays ignorant, which is exactly the property Onion is protecting.


9

Change Impact: What Happens When Entities Change

This section deserves the most attention, because it exposes the central tension of the pattern — and it's the question most articles skip.

9.1 The core tension: dependencies point in, changes ripple out

DIAGRAM 12
flowchart LR subgraph T["The two opposing directions"] direction TB A["COMPILE-TIME DEPENDENCY<br/>Presentation → Application → Domain<br/>points INWARD"] B["CHANGE PROPAGATION<br/>Domain → Application → Presentation/Infra<br/>ripples OUTWARD"] end A -.->|"are exactly opposite"| B

Put plainly: you made the most-depended-upon thing the most business-volatile thing. The domain is at the centre, so everything depends on it; but the domain is also where business change lands first. A change to Order can, in the worst case, touch every project in the solution.

This is not a flaw in your implementation. It's an inherent, deliberate trade, and understanding it is the difference between using the pattern well and cargo-culting it. Onion's bet is:

Business rules change often but locally; infrastructure changes rarely but globally. So make infrastructure change cheap by isolating it, and accept that business change is visible.

If your system's actual change profile is the reverse — stable rules, churning infrastructure — Onion pays off enormously. If it's stable infrastructure and churning rules, you're paying overhead for insurance you don't need. This is the real "when not to use it" test, more than team size or LOC.

9.2 A taxonomy of entity changes

Not all entity changes ripple equally. Classify before you panic:

DIAGRAM 13
flowchart TD START{"An entity needs to change"} --> Q1{"Does the change alter<br/>the entity's PUBLIC shape?"} Q1 -->|"No — internal only"| C1["CLASS A: Encapsulated<br/>Blast radius: Domain only"] Q1 -->|Yes| Q2{"Is it purely ADDITIVE?"} Q2 -->|"Yes — new optional member"| C2["CLASS B: Additive<br/>Domain + Persistence<br/>+ optionally outward"] Q2 -->|No| Q3{"Does it change an<br/>INVARIANT or state machine?"} Q3 -->|Yes| C3["CLASS C: Semantic<br/>Domain + Application<br/>+ existing DATA"] Q3 -->|No| Q4{"Does it change identity,<br/>type, or aggregate boundary?"} Q4 -->|Yes| C4["CLASS D: Structural<br/>EVERY layer + migration<br/>+ API version"] Q4 -->|No| C5["CLASS E: Rename / remove<br/>Mechanical but wide"]

9.3 The impact matrix

Read this as: for change type X, which layers must I touch? ● = must change · ◐ = usually changes · ○ = may change · – = untouched

# Change to an entity ① Domain ② Dom.Svc ③ App Contracts/DTO ④ Persistence Migration ④ API Consumers Tests
1 Add a private field / refactor internals ● – – – ◐ ◐ – – ○
2 Add a computed property (Total) ● – ○ ○ ● Ignore() – ○ – ●
3 Add a new behaviour/method ● ○ ◐ ○ – – ◐ ○ ●
4 Add an optional/nullable property ● – ○ ◐ ● ● ◐ ○ ●
5 Add a required property ● ○ ● ● ● ● 3-step ● ● ●
6 Rename a property ● ◐ ● ◐ ● ● ○ ○ ●
7 Remove a property ● ◐ ● ● ● ● ● ● ●
8 Change a primitive → Value Object ● ◐ ● ○ ● conv. ◐ – – ●
9 Tighten an invariant (rule change) ● ○ ○ – – ◐ backfill – ◐ ●
10 Add a state to the state machine ● ◐ ● ● ● ● ● ● ●
11 Change identity type (int→Guid) ● ● ● ● ● ● hard ● ● ●
12 Change relationship cardinality (1:N→N:M) ● ● ● ● ● ● ● ● ●
13 Split / move across aggregate boundary ● ● ● ● ● ● ● ● ●
14 Add a domain event ● ◐ ○ – ○ outbox ○ – ◐ ●
15 Change a column type only (no domain change) – – – – ● ● – – ○

Row 15 is the payoff row. A pure infrastructure change touches exactly one layer. That is what you bought. Rows 11–13 are the cost rows. Structural domain changes touch everything, and no amount of layering prevents that — layering only makes the compiler tell you where.

9.4 Walkthrough: adding a required property

The most common non-trivial case. Say Order now needs a required DeliveryAddress.

DIAGRAM 14
flowchart TD A["① Domain: add Address value object<br/>add required param to Order.Place<br/>add invariant: address must be complete"] --> B["🔴 BUILD BREAKS<br/>every caller of Order.Place"] B --> C["③ Application: OrderService.PlaceAsync<br/>must now supply an address"] C --> D["Contracts: PlaceOrderRequest gains<br/>DeliveryAddress; OrderDto exposes it"] D --> E["④ API: request schema changes<br/>→ breaking change for clients"] C --> F["④ Persistence: OwnsOne mapping<br/>for Address in OrderConfiguration"] F --> G["Migration: existing rows have<br/>NO address — cannot add NOT NULL"] G --> H["Expand/contract migration required"] A --> I["Tests: every Order test fixture<br/>and builder must supply an address"] E --> J["Consumers: mobile app, partner<br/>integrations, internal callers"]

The compiler breaking is the feature, not the bug. In an N-tier system where Order is a bag of public setters, adding a required field compiles fine and fails at 3am in production when SaveChanges hits a NOT NULL constraint. Here, the build stops and enumerates every site that must be reconsidered. Onion converts a runtime failure into a compile-time worklist.

The expand/contract (a.k.a. parallel change) migration that step H demands:

DIAGRAM 15
sequenceDiagram autonumber participant D as Domain participant DB as Database participant OLD as Old app version participant NEW as New app version rect rgb(20,60,45) Note over D,DB: PHASE 1 — EXPAND (backwards compatible) D->>DB: Migration: ADD DeliveryAddress_* columns as NULLABLE Note over OLD,NEW: both versions run fine — old ignores new columns end rect rgb(120,90,20) Note over D,DB: PHASE 2 — MIGRATE NEW->>DB: deploy: writes populate the new columns NEW->>DB: backfill job fills historical rows NEW->>NEW: domain treats address as optional (nullable) for now end rect rgb(90,30,20) Note over D,DB: PHASE 3 — CONTRACT D->>D: make DeliveryAddress required in the aggregate D->>DB: Migration: ALTER COLUMN ... NOT NULL D->>D: remove the nullable-tolerant code path end

Never do this in one migration on a live system. The three-phase shape is not Onion-specific, but Onion makes it visible, because the domain's invariant and the database's constraint are two separate artefacts you must consciously keep in step.

9.5 Walkthrough: primitive → value object

Changing Order.Currency from string to a Currency value object.

Layer What changes Why
① Domain string Currency → Currency Currency; add Currency VO with ISO validation The rule "currency must be valid ISO-4217" now has a home
② Domain Services Signatures taking string currency update Compiler-driven
③ Application Construct new Currency(request.Currency) at the boundary Translation is an application job
Contracts Unchanged — DTO keeps string Currency DTOs are serialisation shapes; keep them primitive
④ Persistence Add HasConversion(c => c.Code, v => new Currency(v)) ORM absorbs the mismatch
Migration None — column stays nvarchar(3) Value converter is a mapping, not a schema change
④ API Unchanged Contract is stable
Consumers Unchanged No visible change

This is the best-case shape: a meaningful domain improvement that is completely invisible to the outside world. The DTO layer and the value-converter layer between them absorb 100% of the ripple. When people ask "what do all these DTOs and mapping classes actually buy me?" — this is the answer.

Corollary and warning: if your DTOs are your entities (i.e. you serialise Order directly), you lose this entirely. Every internal refactor becomes a public API change. Reusing entities as DTOs is the single change that converts Onion into expensive N-tier.

9.6 Walkthrough: changing an invariant

Suppose the manual-approval threshold drops from £10,000 to £5,000.

DIAGRAM 16
flowchart TD A["① Domain: change threshold constant<br/>or inject a policy"] --> B{"Does existing data<br/>violate the new rule?"} B -->|No| C["Done. One line changed.<br/>Blast radius: 1 file + 1 test."] B -->|Yes| D["⚠️ Historical rows now violate<br/>an invariant the aggregate enforces"] D --> E{"Where is the rule enforced?"} E -->|"On state transition only<br/>(Confirm)"| F["Safe: old confirmed orders<br/>are never re-validated"] E -->|"In the constructor /<br/>on every materialisation"| G["🔴 DANGER: loading an old<br/>order now THROWS"] G --> H["Options: (a) backfill/quarantine data<br/>(b) version the rule by PlacedOn<br/>(c) relax constructor, validate on transition"]

This is a subtle and genuinely dangerous failure mode specific to rich domain models, and it deserves a rule:

Enforce invariants on state transitions, not on rehydration. EF Core materialises entities via the private parameterless constructor precisely so it can bypass your factory. If you also validate in the private constructor, tightening any rule retroactively invalidates history and your app starts throwing on SELECT.

Where a rule genuinely must change over time, make it explicit rather than implicit — inject an IApprovalPolicy resolved by PlacedOn, or store the version of the rule that applied when the order was created. Business rules have effective dates; pretending they're eternal constants is what causes the 3am incident.

9.7 Walkthrough: splitting an aggregate

The heaviest change. Order grows a Shipment concept that becomes its own aggregate root.

DIAGRAM 17
flowchart TD subgraph BEFORE_G["Before"] O1["Order (root)"] --> L1["OrderLine"] O1 --> S1["ShipmentInfo (member)"] end subgraph AFTER_G["After"] O2["Order (root)"] --> L2["OrderLine"] S2["Shipment (root)"] -.->|"references by ID only"| O2 end BEFORE_G --> AFTER_G

Everything moves:

Layer Impact
① Domain New Shipment root + IShipmentRepository; Order loses direct navigation, keeps ShipmentId or nothing at all
② Domain Services Any rule spanning both now must become a domain service — it can no longer live on Order
③ Application Use cases that touched both now coordinate two aggregates = two consistency boundaries. Decide: single transaction (pragmatic) or eventual consistency via domain events (purist)
Contracts OrderDto loses shipment fields; new ShipmentDto; possibly a composite read model for the UI
④ Persistence New DbSet, new configuration, FK direction may reverse
Migration Table split or FK move; data migration required
④ API New /shipments resource; /orders/{id} response shrinks — breaking; needs API versioning
Consumers Clients must call two endpoints or you provide a BFF/composite endpoint

The lesson: aggregate boundaries are the most expensive decision in the whole design. Layer boundaries are cheap to adjust; aggregate boundaries are not. Spend your modelling effort there. Get the transaction/consistency boundary right and the layering mostly falls out; get it wrong and no amount of clean layering saves you.

9.8 How to dampen the ripple

Six techniques, in descending order of value:

  1. Never expose entities across a process boundary. DTOs in Contracts are the firewall. This is what makes §9.5 possible.
  2. Keep DTOs primitive-shaped and versioned separately from the domain. OrderDtoV1 / OrderDtoV2 co-existing is normal and healthy.
  3. Validate on transition, not on load (§9.6).
  4. Use expand/contract for every schema change on a running system (§9.4).
  5. Use an anti-corruption layer for external models. A partner's CustomerRecord never becomes your Customer — translate at the edge, in Infrastructure.
  6. Prefer additive change. Adding a new method to an aggregate ripples far less than changing an existing signature. New use case → new handler, not a new parameter on an old one.

And one meta-technique: make the blast radius visible in code review. A PR that touches Domain + Application + Contracts + API in one commit is a Class C/D change and should be reviewed as an architectural decision, not as a feature. A PR touching only Persistence is routine. The project structure gives you that signal for free — use it.


10

Testing Strategy Per Layer

Onion's biggest practical payoff is testability, but only if you test each layer the way it wants to be tested.

DIAGRAM 18
flowchart TD subgraph PY["Test pyramid mapped to Onion layers"] direction TB T5["④ Architecture / fitness tests<br/><i>seconds · a handful · run every build</i>"] T4["④ Functional / E2E — WebApplicationFactory + Testcontainers<br/><i>minutes · dozens · happy paths + critical failures</i>"] T3["④ Integration — Persistence against a real DB<br/><i>seconds · scores · every repository + mapping</i>"] T2["③ Application — use cases with test doubles<br/><i>ms · hundreds · orchestration + policy</i>"] T1["① ② Domain — pure unit tests, NO mocks<br/><i>μs · thousands · every invariant</i>"] end T1 --- T2 --- T3 --- T4 --- T5

10.1 ① Domain tests — the point of the whole exercise

No mocks. No fakes. No fixtures. No container. If you need a mock to test a domain rule, the rule is in the wrong place.

C#
public class OrderTests
{
    private static readonly IClock Clock = new FixedClock(
        new DateTimeOffset(2026, 8, 12, 9, 0, 0, TimeSpan.Zero));

    [Fact]
    public void Confirm_WithNoLines_Throws()
    {
        var order = Order.Place(CustomerId.New(), "GBP", Clock);

        var act = () => order.Confirm(Clock);

        act.Should().Throw<DomainException>()
           .WithMessage("*at least one line*");
    }

    [Fact]
    public void AddLine_WithMismatchedCurrency_Throws()
    {
        var order = Order.Place(CustomerId.New(), "GBP", Clock);

        var act = () => order.AddLine(new Sku("ABC"), 1, new Money(10m, "USD"));

        act.Should().Throw<DomainException>().WithMessage("*does not match*");
    }

    [Theory]
    [InlineData(9_999.99, false)]
    [InlineData(10_000.00, false)]
    [InlineData(10_000.01, true)]
    public void RequiresManualApproval_AtThresholdBoundary(decimal total, bool expected)
    {
        var order = Order.Place(CustomerId.New(), "GBP", Clock);
        order.AddLine(new Sku("ABC"), 1, new Money(total, "GBP"));

        order.RequiresManualApproval.Should().Be(expected);
    }

    [Fact]
    public void AddLine_AfterConfirmation_Throws()
    {
        var order = Order.Place(CustomerId.New(), "GBP", Clock);
        order.AddLine(new Sku("ABC"), 1, new Money(50m, "GBP"));
        order.Confirm(Clock);

        var act = () => order.AddLine(new Sku("XYZ"), 1, new Money(5m, "GBP"));

        act.Should().Throw<DomainException>().WithMessage("*can no longer be modified*");
    }

    [Fact]
    public void Confirm_RaisesOrderConfirmed()
    {
        var order = Order.Place(CustomerId.New(), "GBP", Clock);
        order.AddLine(new Sku("ABC"), 2, new Money(25m, "GBP"));

        order.Confirm(Clock);

        order.DomainEvents.OfType<OrderConfirmed>().Should().ContainSingle()
             .Which.Total.Should().Be(new Money(50m, "GBP"));
    }
}

These run in microseconds and never break because someone changed a connection string. This is what tenet 4 was for. If any of these tests needed a Mock<IOrderRepository>, the design would be wrong.

Value objects deserve property-based tests:

C#
[Property]
public Property Money_Addition_IsCommutative(decimal a, decimal b) =>
    (new Money(Round(a), "GBP") + new Money(Round(b), "GBP")
     == new Money(Round(b), "GBP") + new Money(Round(a), "GBP")).ToProperty();

10.2 ③ Application tests — orchestration only

Here you do use test doubles, because the ports are yours and were designed to be substituted. Test the orchestration and application policy — never re-test domain rules at this level.

C#
public class OrderServiceTests
{
    private readonly IOrderRepository _orders = Substitute.For<IOrderRepository>();
    private readonly ICustomerRepository _customers = Substitute.For<ICustomerRepository>();
    private readonly IUnitOfWork _uow = Substitute.For<IUnitOfWork>();
    private readonly IClock _clock = new FixedClock(DateTimeOffset.UnixEpoch);

    private OrderService Sut => new(_orders, _customers, _uow, _clock, NullLogger<OrderService>.Instance);

    [Fact]
    public async Task PlaceAsync_UnknownCustomer_ThrowsNotFound_AndDoesNotPersist()
    {
        _customers.ExistsAsync(Arg.Any<CustomerId>(), Arg.Any<CancellationToken>())
                  .Returns(false);

        var act = () => Sut.PlaceAsync(ValidRequest());

        await act.Should().ThrowAsync<NotFoundException>();
        _orders.DidNotReceive().Add(Arg.Any<Order>());
        await _uow.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
    }

    [Fact]
    public async Task PlaceAsync_Success_SavesExactlyOnce()
    {
        _customers.ExistsAsync(Arg.Any<CustomerId>(), Arg.Any<CancellationToken>()).Returns(true);

        await Sut.PlaceAsync(ValidRequest());

        _orders.Received(1).Add(Arg.Any<Order>());
        await _uow.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
    }
}

Consider fake repositories over mocks for anything non-trivial — an InMemoryOrderRepository : IOrderRepository backed by a Dictionary produces far more readable tests than five lines of Substitute.For setup, and it's ~20 lines you write once.

10.3 ④ Persistence tests — against a real database

Never UseInMemoryDatabase for these. It doesn't enforce constraints, doesn't translate LINQ identically, and will let bugs through. Microsoft's own guidance has moved away from it. Use Testcontainers:

C#
public sealed class PersistenceFixture : IAsyncLifetime
{
    private readonly MsSqlContainer _db = new MsSqlBuilder()
        .WithImage("mcr.microsoft.com/mssql/server:2022-latest").Build();

    public ShopDbContext Context { get; private set; } = null!;

    public async Task InitializeAsync()
    {
        await _db.StartAsync();
        var opts = new DbContextOptionsBuilder<ShopDbContext>()
            .UseSqlServer(_db.GetConnectionString()).Options;
        Context = new ShopDbContext(opts);
        await Context.Database.MigrateAsync();
    }

    public Task DisposeAsync() => _db.DisposeAsync().AsTask();
}

public class OrderRepositoryTests(PersistenceFixture fx) : IClassFixture<PersistenceFixture>
{
    [Fact]
    public async Task Roundtrip_PreservesValueObjectsAndPrivateCollection()
    {
        var order = Order.Place(CustomerId.New(), "GBP", SystemClock.Instance);
        order.AddLine(new Sku("WIDGET-1"), 3, new Money(19.99m, "GBP"));
        order.Confirm(SystemClock.Instance);

        var repo = new OrderRepository(fx.Context);
        repo.Add(order);
        await fx.Context.SaveChangesAsync();
        fx.Context.ChangeTracker.Clear();          // force a real DB read

        var loaded = await repo.FindAsync(order.Id);

        loaded.Should().NotBeNull();
        loaded!.Lines.Should().ContainSingle();
        loaded.Total.Should().Be(new Money(59.97m, "GBP"));   // ← the real assertion
        loaded.Status.Should().Be(OrderStatus.Confirmed);
    }
}

The ChangeTracker.Clear() is essential — without it you're asserting against the object you just put in memory, and the test passes even when the mapping is broken.

What to test here: value-converter round-trips, owned-type mapping, private backing field materialisation, precision/scale on decimals, concurrency tokens, cascade behaviour, and every non-trivial repository query. Also: run dotnet ef migrations script in CI and diff it — silent model drift is a real failure mode.

10.4 ④ Functional tests — through the API

C#
public class PlaceOrderEndpointTests(ApiFactory factory) : IClassFixture<ApiFactory>
{
    [Fact]
    public async Task PlaceOrder_AboveThreshold_Returns400WithProblemDetails()
    {
        var client = factory.CreateClient();

        var res = await client.PostAsJsonAsync("/api/v1/orders", new PlaceOrderRequest(
            SeedData.CustomerId, "GBP",
            [new PlaceOrderLine("BIG-ITEM", 2, 7_500m)]));

        res.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        var problem = await res.Content.ReadFromJsonAsync<ProblemDetails>();
        problem!.Title.Should().Be("Business rule violated");
    }
}

Keep these few. They're slow, and their job is to prove the wiring works — that DI resolves, middleware maps exceptions, serialisation round-trips — not to re-test business rules.

10.5 ④ Architecture tests — the layer that keeps the layers

Documentation doesn't enforce architecture; tests do. Without automated validation, boundaries erode one shortcut at a time until the layers are meaningless. Two mature .NET options, both inspired by Java's ArchUnit: NetArchTest.Rules (lightweight, fluent) and ArchUnitNET (more expressive, supports declared architecture models). Both work by reflecting over compiled assemblies.

C#
public class ArchitectureTests
{
    private static readonly Assembly Domain     = typeof(Order).Assembly;
    private static readonly Assembly Application = typeof(OrderService).Assembly;
    private static readonly Assembly Persistence = typeof(ShopDbContext).Assembly;
    private static readonly Assembly Api         = typeof(Program).Assembly;

    [Fact]
    public void Domain_Should_Not_Depend_On_Anything()
    {
        var result = Types.InAssembly(Domain)
            .ShouldNot()
            .HaveDependencyOnAny(
                "OnionShop.Application", "OnionShop.Persistence",
                "OnionShop.Infrastructure", "OnionShop.Api",
                "Microsoft.EntityFrameworkCore", "Microsoft.AspNetCore")
            .GetResult();

        result.IsSuccessful.Should().BeTrue(
            because: string.Join(", ", result.FailingTypeNames ?? []));
    }

    [Fact]
    public void Application_Should_Not_Depend_On_Infrastructure_Or_Presentation()
    {
        Types.InAssembly(Application)
            .ShouldNot().HaveDependencyOnAny(
                "OnionShop.Persistence", "OnionShop.Infrastructure", "OnionShop.Api")
            .GetResult().IsSuccessful.Should().BeTrue();
    }

    [Fact]
    public void Persistence_Should_Only_Depend_On_Domain()
    {
        Types.InAssembly(Persistence)
            .ShouldNot().HaveDependencyOnAny("OnionShop.Application", "OnionShop.Api")
            .GetResult().IsSuccessful.Should().BeTrue();
    }

    [Fact]
    public void Entities_Should_Have_Private_Parameterless_Constructor()
    {
        var entities = Types.InAssembly(Domain)
            .That().Inherit(typeof(AggregateRoot<>)).GetTypes();

        entities.Should().OnlyContain(t =>
            t.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)
             .Any(c => c.GetParameters().Length == 0));
    }

    [Fact]
    public void Entities_Should_Not_Expose_Public_Setters()
    {
        var offenders = Types.InAssembly(Domain)
            .That().Inherit(typeof(AggregateRoot<>)).GetTypes()
            .SelectMany(t => t.GetProperties())
            .Where(p => p.SetMethod?.IsPublic == true)
            .Select(p => $"{p.DeclaringType!.Name}.{p.Name}")
            .ToList();

        offenders.Should().BeEmpty("aggregates must be mutated through behaviour, not setters");
    }

    [Fact]
    public void Repository_Interfaces_Live_In_Domain_Implementations_In_Persistence()
    {
        Types.InAssembly(Persistence)
            .That().ImplementInterface(typeof(IOrderRepository))
            .Should().ResideInNamespace("OnionShop.Persistence.Repositories")
            .And().NotBePublic()
            .GetResult().IsSuccessful.Should().BeTrue();
    }

    [Fact]
    public void Application_Services_Should_Be_Sealed_And_Internal()
    {
        Types.InAssembly(Application)
            .That().HaveNameEndingWith("Service").And().AreClasses()
            .Should().BeSealed().And().NotBePublic()
            .GetResult().IsSuccessful.Should().BeTrue();
    }
}

Add these on day one, not day 400. They cost an hour and they are the only thing standing between your solution and gradual decay into N-tier-with-nicer-folder-names. Catching a violation in a failing test is dramatically cheaper than catching it in code review, and cheaper still than not catching it.

One caveat worth knowing: because of how .NET compiles, reflection-based tools can occasionally miss dependencies that the compiler optimised away (e.g. inlined constants), so treat them as a strong net, not a proof.

10.6 Test-to-layer summary

Layer Test type Doubles? Speed Count What breaks the test
① Domain Unit / property-based None μs Hundreds–thousands A business rule changed
② Domain Services Unit None or in-memory μs Dozens A cross-entity rule changed
③ Application Unit Fakes > mocks ms Hundreds Orchestration or policy changed
④ Persistence Integration (Testcontainers) Real DB s Scores Mapping, query, or schema changed
④ Infrastructure Integration (WireMock) Stub server s Dozens External contract changed
④ Presentation Functional (WebApplicationFactory) Real stack s Dozens Wiring or HTTP contract changed
All Architecture / fitness — s ~10 Someone violated a boundary

11

When To Use It — And When Not To

11.1 The decision tree

DIAGRAM 19
flowchart TD S{"Should I use Onion Architecture?"} --> A{"Expected lifetime<br/>> 2–3 years?"} A -->|No| N1["❌ Don't. Ship a modular monolith<br/>or vertical slices."] A -->|Yes| B{"Is there real business<br/>complexity — invariants, workflows,<br/>rules an expert must explain?"} B -->|"No — it's CRUD"| N2["❌ Don't. You'll build<br/>an anemic model with 5 layers<br/>of pass-through."] B -->|Yes| C{"Will infrastructure change<br/>or need to be substituted?<br/>(DB, provider, delivery mechanism)"} C -->|Never| D{"Is testability of rules<br/>without I/O a hard requirement?"} C -->|Likely| Y1["✅ Strong fit"] D -->|No| N3["⚠️ Marginal. Consider<br/>vertical slices with a rich domain."] D -->|Yes| Y2["✅ Good fit"] Y1 --> E{"Does the team understand<br/>DI, DIP and DDD tactics?"} Y2 --> E E -->|No| N4["⚠️ Train first, or you'll get<br/>cargo-cult Onion: the folders<br/>without the benefits."] E -->|Yes| Y3["✅ Do it. Add architecture<br/>tests on day one."]

11.2 Use it when

  • The system is long-lived. Palermo's own framing: appropriate for long-lived business applications, explicitly not for small websites. Core banking, insurance underwriting, logistics, ERP, healthcare records, trading systems, anything regulated.
  • The domain has genuine invariants. Rules that must hold regardless of which entry point is used, that a domain expert can state and argue about, and that change over time.
  • Multiple delivery mechanisms. REST API + gRPC + scheduled jobs + admin UI + partner webhook all invoking the same use cases. The Application layer becomes the single definition of "what this system does".
  • Infrastructure is genuinely uncertain or plural. On-prem SQL for one customer, Postgres for another; a legacy system being strangled; a vendor you expect to replace.
  • Compliance requires demonstrable test coverage of business rules. Auditors love "here are 800 tests that prove our rules, none of which touch a database."
  • Multiple teams, one codebase. Physical project boundaries + architecture tests give you enforceable ownership lines without microservices.
  • You expect the team to churn. Explicit structure is a knowledge-transfer mechanism. New joiners can find things.

11.3 Don't use it when

  • It's CRUD. An admin panel that maps forms to tables has no domain. Layering it produces an anemic model — entities with no behaviour, all logic in services — which is the anti-pattern Fowler named precisely because it takes the cost of OO design while getting none of the benefit. Use minimal APIs + EF Core directly, or a scaffolded framework.
  • The system is short-lived. Prototypes, campaign microsites, internal tools with a one-year horizon, hackathon output, spike code.
  • The team is small and the domain is simple. Five projects and four abstractions per feature will slow a two-person team down more than the coupling ever would.
  • A tiny microservice. A service with three endpoints and one table doesn't need six projects. One project with folders, or vertical slices, is honest.
  • Ultra-low latency is the dominant constraint. Every mapping hop costs allocations. If you're counting nanoseconds, the indirection is real cost — though note this is rarely the actual bottleneck, and profiling should precede this argument.
  • The team doesn't understand DIP. Onion without genuine dependency inversion is N-tier with more projects: all the ceremony, none of the payoff. It's the most expensive possible outcome.
  • Data-shaped problems. Reporting, ETL, analytics, BI. There's no domain model to protect; the data is the model. Use the tools built for it.

11.4 The honest middle ground

Most real systems are not uniformly complex. A single application typically has:

  • 2–3 genuinely complex subdomains (pricing, eligibility, settlement) — full Onion, rich aggregates, worth every abstraction
  • 5–10 supporting subdomains (notifications, audit, reference data) — thin slices, direct EF Core, no repository
  • A long tail of CRUD — scaffold it

Applying maximum ceremony uniformly is the most common failure. Segment by subdomain complexity. A modular monolith where each module chooses its own internal architecture is, in 2026, probably the most defensible default for a large system — and it is entirely compatible with Onion inside the modules that need it.


12

Pros and Cons, Honestly

12.1 Pros

Benefit What it actually buys you
Testable business rules Domain tests need no mocks, no DB, no container. Thousands of them run in under a second. This is the largest single benefit and it compounds.
Infrastructure independence Swapping SQL Server → Postgres, or Stripe → Adyen, touches one project. Row 15 of the impact matrix.
Enforced separation of concerns Not by convention or code review, but by the compiler and architecture tests.
Change is localised and visible The project a PR touches tells you the blast radius before you read the diff.
Domain-first modelling The model is shaped by the business, not by the DBA or the serialiser. Ubiquitous language survives contact with the code.
Parallel work Frontend against Contracts, domain team against Domain, platform team against Persistence — real interfaces, minimal collision.
Framework churn tolerance Your business rules survived .NET Framework → .NET Core → .NET 10. They'll survive whatever's next. Genuinely valuable over a decade.
Onboarding Predictable structure. "Where does this go?" has an answer.
Deferred decisions You can build and test the domain before choosing a database.

12.2 Cons

Cost The reality
Indirection tax A trivial feature can touch 6+ files across 4 projects. "Add a nullable field" becomes an afternoon.
Boilerplate & mapping Entity → DTO → ViewModel. Mapping code is tedious and a real bug surface. AutoMapper hides it at the cost of runtime failures and unclear data flow — hand-written mappers or source generators (Mapperly) are increasingly preferred.
Read-path inefficiency Hydrating a full aggregate to render a list is wasteful (§8.3). Needs CQRS-lite, which adds a second path and therefore more architecture.
Repository-over-EF-Core debate EF Core's DbContext is documented by Microsoft as already a Unit of Work + Repository implementation. Wrapping it can duplicate functionality, hide capabilities like split queries, AsNoTracking, projections and compiled queries, and lead to worse SQL — a generic Update() writes every property, whereas EF's change tracking writes only what changed. The "swap the database" justification is largely mythical in practice. Counter-position: in a rich domain the repository isn't about swapping databases, it's about expressing aggregate boundaries and business intent in the ubiquitous language. Both positions are defensible; picking one by default and without reasoning is the actual mistake.
Anemic domain risk Very common. Teams build the layers, then put all logic in services and leave entities as property bags. You now pay every cost and receive none of the benefit.
Learning curve DIP, aggregates, value objects, composition roots. Juniors will violate the rules unknowingly without architecture tests.
Over-abstraction drift IEmailSender with one implementation that will never change is speculative generality — the interface earns its place only when it isolates something volatile or enables a test.
Debugging distance Stack traces cross four assemblies. F12 lands on an interface.
Cross-aggregate transactions get awkward Strict aggregate-per-transaction pushes you toward eventual consistency, sagas, and outboxes — which is correct at scale and enormous overhead below it.
The ripple problem §9.1 — the most-depended-on layer is also the most business-volatile. Structural domain changes touch everything.

12.3 The one-line summary

Onion Architecture trades local simplicity for global changeability. If the system lives long enough for that trade to pay off, it's excellent. If it doesn't, you've bought insurance you'll never claim.


13

Comparison: Layered vs Hexagonal vs Clean vs Onion vs Vertical Slice

13.1 At a glance

Dimension N-Tier / Layered Hexagonal (Ports & Adapters) Onion Clean Vertical Slice
Author / year Fowler, 2002 Cockburn, 2005 Palermo, 2008 Martin, 2012 Bogard, 2018
Primary axis Technical layers Inside vs outside Concentric rings around a domain Concentric rings around use cases Features
Dependency direction Downward, toward the DB Inward, toward the app Inward, toward the domain Inward, toward entities Within a slice
Number of prescribed rings 3–4 2 3–4 (flexible) 4 (named) n/a
Where the DB sits Foundation Driven adapter Outer ring Outer ring Inside the slice
Core organising unit Layer Port Layer + aggregate Use case Feature/request
Coupling risk High (toward DB) Low Low Low Low between slices, duplication within
Main failure mode Domain shaped by schema Under-specified inside Anemic domain, pass-through services Ceremony, handler explosion Duplication, no shared model
Best for Simple, short-lived Any system needing substitutable edges Long-lived, rule-rich domains Long-lived, use-case-rich domains Feature-churny apps, CRUD-heavy services

13.2 Structural comparison

DIAGRAM 20
flowchart TB subgraph V1["N-Tier"] direction TB a1["Presentation"] --> a2["Business"] --> a3["Data Access"] --> a4[("DB")] end subgraph V2["Hexagonal"] direction TB b1["Driving adapters<br/>UI · API · CLI"] --> b2["Application core<br/>+ ports"] b3["Driven adapters<br/>DB · SMTP · Bus"] --> b2 end subgraph V3["Onion"] direction TB c1["Presentation"] --> c2["App Services"] c5["Infrastructure"] --> c2 c2 --> c3["Domain Services"] --> c4["Domain Model"] end subgraph V4["Clean"] direction TB d1["Frameworks & Drivers"] --> d2["Interface Adapters"] --> d3["Use Cases"] --> d4["Entities"] end subgraph V5["Vertical Slice"] direction LR e1["PlaceOrder<br/>endpoint→handler→data"] e2["CancelOrder<br/>endpoint→handler→data"] e3["GetOrders<br/>endpoint→query→data"] end

13.3 Onion vs Hexagonal

Onion is best read as Hexagonal with the inside subdivided. Cockburn's hexagon says "application inside, adapters outside" and stops there. Palermo added internal rings built on DDD concepts. Hexagonal also emphasises symmetry between driving adapters (UI, tests, CLI) and driven adapters (DB, bus) more explicitly than Onion does.

In .NET practice the terms are used almost interchangeably, and that's mostly fine — they impose the same constraint. If someone says "Ports and Adapters" and shows you a solution with Domain, Application, Infrastructure, Api projects, nothing is wrong.

13.4 Onion vs Clean — the genuinely small difference

These are the same architecture with different emphasis. Both isolate the domain from infrastructure; both rely on dependency inversion so outer layers depend on inner abstractions. Clean is essentially a more explicitly-layered variant of Onion.

The real distinction:

Onion Clean
Organising principle of the core Layers around a domain model Use cases explicitly named and exposed
Typical core structure Domain + Services (+ Contracts, Services.Abstractions) Domain + Application with a class per use case
Feel Service-oriented: IOrderService with several methods Handler-oriented: PlaceOrderCommandHandler, CancelOrderCommandHandler
Emphasis Maintenance and separation of concerns Business-logic independence, flexibility, testability
Prescriptiveness Looser — four tenets, layer count is yours Tighter — Entities / Use Cases / Interface Adapters / Frameworks

Practical guidance: tighter rules suit teams that want guardrails and easy onboarding; looser layering suits experienced teams that will exercise judgement. If your priority is complex business logic decoupled from frameworks, Clean's use-case explicitness helps. If your priority is clear layers and structural clarity, Onion is the better fit. Anyone claiming a large functional difference is selling a course.

13.5 Onion vs Vertical Slice — the real modern debate

Bogard's critique is pointed and worth taking seriously: traditional layered/onion/clean architecture is monolithic in its approach, appropriate for only a minority of typical requests in a system, and tends toward mock-heavy tests with rigid dependency rules that produce abstractions around concepts that shouldn't be abstracted — "Controller MUST talk to a Service that MUST use a Repository". His alternative is to treat each request as a distinct use case and let it choose its own approach.

DIAGRAM 21
flowchart LR subgraph HORIZ["Onion — cut horizontally"] direction TB H1["Presentation ————————"] H2["Application ————————"] H3["Domain —————————"] H4["Infrastructure ———————"] end subgraph VERT["Vertical Slice — cut vertically"] direction LR V1["Place<br/>Order"] V2["Cancel<br/>Order"] V3["List<br/>Orders"] V4["Export<br/>Report"] end
Onion Vertical Slice
Adding a feature Touch every layer Add one folder
Removing a feature Hunt through layers Delete one folder
Coupling Low between layers Low between slices
Cohesion Low per feature (spread out) High per feature
Code duplication Low (shared abstractions) Higher by design; extract shared services/repositories when it hurts
Reads vs writes Same path (awkward) Each slice picks its own — a query slice can use Dapper directly
Consistency Enforced by structure Requires discipline; slices can drift apart
Cross-slice logic Natural (shared domain) Awkward — the "Books slice needs User data" problem
Onboarding Structure is discoverable Must read slices to learn the system

They are not mutually exclusive, and this is the practically important point. The most common productive arrangement in .NET today:

  • Domain layer stays — a rich, shared, invariant-enforcing model. Slices don't get to each invent their own Order.
  • Application layer becomes slices — one folder per use case, each with its command/query, handler, validator, and DTO co-located. If you use MediatR, you're already doing this: MediatR handlers are vertical slices, and MediatR and VSA share the same author.
  • Infrastructure stays — shared adapters.
  • Query slices bypass the aggregate and project straight to DTOs.

That hybrid keeps the ripple-dampening of Onion (§9.5) and the cohesion of slices, and it's what most well-run .NET codebases converge on. Note also the counter-argument that VSA doesn't "evolve" from Clean/Onion by merging projects — it challenges different assumptions, and treating one as a refactor of the other reflects copying rather than understanding.

13.6 Choosing

DIAGRAM 22
flowchart TD Q1{"Rich invariants that must hold<br/>across every entry point?"} -->|Yes| Q2{"Many use cases that vary<br/>a lot in shape?"} Q1 -->|No| Q3{"Mostly CRUD + queries?"} Q2 -->|Yes| R1["Onion/Clean core<br/>+ vertical slices in Application"] Q2 -->|No| R2["Onion or Clean<br/>service-oriented"] Q3 -->|Yes| R3["Vertical Slice or<br/>minimal API + EF Core"] Q3 -->|No| R4["Modular monolith:<br/>per-module choice"]

14

Common Mistakes and Anti-Patterns

14.1 The anemic domain model

Symptom: entities are property bags with public getters and setters. All logic lives in *Service classes. OrderService.Confirm(order) mutates order.Status = "Confirmed" from outside.

Why it's fatal here: Fowler named this an anti-pattern because it is contrary to the basic idea of object-oriented design — combining data and process. In an Onion solution specifically, it means you've built five layers of scaffolding around a data structure. You pay every cost in §12.2 and receive none of the benefits in §12.1. This is the most common way Onion projects fail, and it fails silently — the folders look right.

Test for it: open your largest entity. Count public setters vs. public methods that aren't getters. If setters win, you have an anemic model.

Fix: private setters, factory methods, behaviour methods that enforce invariants (see §7.2). Add the architecture test from §10.5.

14.2 Entities as DTOs

Symptom: [JsonPropertyName] on Order; the controller returns the entity directly.

Why it's fatal: you have coupled your public API to your internal model. Every domain refactor becomes a breaking API change, destroying the property demonstrated in §9.5. You also risk over-posting and accidental data disclosure (lazy-loaded navigation properties serialising the entire object graph).

Fix: always map. Keep DTOs in Contracts. Version them independently.

14.3 The generic repository

C#
// ❌
public interface IRepository<T> where T : class
{
    IQueryable<T> Query();
    Task<List<T>> GetAllAsync();
    Task<T?> GetByIdAsync(int id);
    Task AddAsync(T entity);
    Task UpdateAsync(T entity);
    Task DeleteAsync(int id);
}

Three problems. First, IQueryable<T> leaks the ORM's expression-translation semantics through an interface that pretends to be persistence-agnostic. Second, one repository per entity rather than per aggregate root dissolves the aggregate boundary — if IRepository<OrderLine> exists, anyone can mutate a line without going through Order, and the invariants are gone. Third, as Neil Ford put it, the more reusable code is, the less usable it is: generic repositories work at the start and accumulate special-case methods until each one is bespoke anyway.

Fix: one interface per aggregate root, with methods named after what the domain actually needs (§7.3).

14.4 The pass-through service

C#
// ❌ adds zero value, costs a file and a hop
public class OrderService(IOrderRepository repo) : IOrderService
{
    public Task<Order?> GetAsync(Guid id) => repo.FindAsync(new OrderId(id));
}

Remember Palermo's rule: any outer layer may call any inner layer directly. If the Application layer has nothing to add, let Presentation call the port. Don't manufacture proxy classes to satisfy a layering scheme Onion never required.

14.5 Leaking infrastructure into the core

Every one of these is a violation, and all of them are common:

Leak Where you'll find it
[Table], [Column], [Key] attributes on entities Domain (use IEntityTypeConfiguration<T> instead)
IQueryable<T> in a repository interface Domain
HttpContext / IHttpContextAccessor Application (pass a CurrentUser value object in instead)
DbContext injected into a domain service Domain Services
System.Data.SqlClient exception types caught in Application Application (translate at the Infrastructure boundary)
Task.Delay / DateTime.Now in an entity Domain (inject IClock)
ILogger inside an aggregate Domain (aggregates shouldn't log; raise events)
Microsoft.EntityFrameworkCore in Domain.csproj The .csproj — check it in CI

14.6 Onion for one microservice with three endpoints

Six projects, four abstractions, one table. The ceremony exceeds the problem by an order of magnitude. Use one project with folders. You can always split later — it's a mechanical refactor, and doing it when the pain arrives is cheaper than guessing.

14.7 Treating architecture as a religion

Architecture is a choice, not a doctrine, and the professional habit is to keep asking why a project is structured the way it is rather than copying a diagram. Concretely, allow yourself to:

  • Skip the repository for a genuinely simple read path.
  • Put a query handler in Application that uses Dapper directly against a read model.
  • Merge Contracts into Application on a small service.
  • Let a supporting subdomain be plain CRUD inside an otherwise Onion solution.

What you should not relax: the direction of dependencies. That's the one rule that generates the value. Everything else is negotiable.

14.8 No architecture tests

Boundaries erode one shortcut at a time until the layers are meaningless. Prevention beats detection: a failing test at commit time is cheaper than a code review comment, which is cheaper than an architectural review in year three. §10.5. There is no excuse; it's an hour of work.


15

Adoption Path and ADR Template

15.1 Incremental adoption from an existing N-tier codebase

You don't need a big-bang rewrite. The order below is deliberate — each step is independently valuable and independently revertible.

DIAGRAM 23
flowchart TD S1["1. Add a Domain project with NO references.<br/>Move POCOs into it. Nothing else changes."] --> S2["2. Add architecture tests<br/>asserting Domain depends on nothing.<br/>Watch them fail. Fix the leaks."] S2 --> S3["3. Move behaviour into entities,<br/>one aggregate at a time.<br/>Start with the most rule-heavy."] S3 --> S4["4. Define repository interfaces in Domain<br/>for one aggregate. Implement in the<br/>existing DAL. Invert one arrow."] S4 --> S5["5. Introduce DTOs at the API boundary.<br/>Stop serialising entities."] S5 --> S6["6. Extract an Application project;<br/>move orchestration out of controllers."] S6 --> S7["7. Move the DAL to Infrastructure.<br/>The reference now points inward."] S7 --> S8["8. Tighten: private setters,<br/>value objects, domain events."]

Step 2 before step 3 is not a typo. Establishing the fitness function first means every subsequent step is verified rather than hoped for, and the initial failure list becomes your actual backlog.

15.2 ADR template

Markdown
# ADR-00X: Adopt Onion Architecture for <system>

## Status
Proposed | Accepted | Superseded by ADR-00Y

## Context
- Expected system lifetime: <years>
- Domain complexity: <describe the invariants and workflows>
- Change profile: <what changes often — rules or infrastructure?>
- Team size and DDD/DIP experience: <...>
- Delivery mechanisms: <REST, gRPC, jobs, UI, ...>
- Known infrastructure volatility: <...>

## Decision
We will structure <system> using Onion Architecture with the following layers:
<list projects and their reference rules>

We will NOT apply it to <these subdomains>, which are CRUD and will use <alternative>.

## Consequences
### Positive
- Business rules unit-testable without I/O
- Infrastructure substitutable at the edge
- Boundaries enforced by compiler + architecture tests

### Negative
- ~N extra projects; higher per-feature file count
- Mapping overhead between entities and DTOs
- Read paths require a separate query approach (CQRS-lite)
- Structural domain changes ripple outward (accepted trade)

## Guardrails
- Architecture tests in CI from day one (NetArchTest / ArchUnitNET)
- Domain.csproj must have zero PackageReference entries
- No entity may be serialised on a public contract
- Repository interfaces: one per aggregate root, no IQueryable

## Alternatives considered
- Vertical Slice Architecture: rejected because <...>
- Modular monolith with per-module choice: <...>
- N-tier: rejected because <...>

## Revisit when
- The domain turns out to be thinner than expected
- Read-path performance becomes the dominant constraint
- Team composition changes materially

16

Reference Checklist

Print this. Use it in code review.

Structure

  • ✅ Domain.csproj has zero PackageReference and zero ProjectReference
  • ✅ No Microsoft.EntityFrameworkCore or Microsoft.AspNetCore anywhere in Core
  • ✅ Core projects compile in a solution containing only Core projects
  • ✅ Exactly one composition root; no new ConcreteService() outside it
  • ✅ Repository interfaces live in Domain; implementations are internal in Persistence

Domain

  • ✅ Entities have private setters and a private parameterless constructor
  • ✅ Aggregates expose IReadOnlyList<T>, never List<T>
  • ✅ Creation goes through factory methods, not public constructors
  • ✅ Invariants are enforced on state transitions, not on rehydration
  • ✅ Value objects are immutable and validate in their constructor
  • ✅ One repository per aggregate root; no IQueryable in any signature
  • ✅ Primitives are wrapped where they carry meaning (Money, Sku, OrderId)
  • ✅ Domain events are plain records with no framework base type

Application

  • ✅ Services orchestrate; they contain no business rules
  • ✅ The transaction boundary is here and nowhere else
  • ✅ Entities are never returned across a process boundary
  • ✅ Ports are defined by the consumer, named for what the domain needs

Infrastructure

  • ✅ EF mapping lives in IEntityTypeConfiguration<T>, not in attributes on entities
  • ✅ External models are translated at the boundary (anti-corruption layer)
  • ✅ Every schema change on a live system uses expand/contract

Testing

  • ✅ Domain tests use no mocks at all
  • ✅ Persistence tests run against a real database (Testcontainers, not InMemory)
  • ✅ Architecture tests exist and run in CI
  • ✅ ChangeTracker.Clear() between write and read in mapping tests

Judgement

  • ✅ Every abstraction isolates something volatile or enables a test — no speculative interfaces
  • ✅ CRUD subdomains are allowed to be CRUD
  • ✅ The read path is allowed to bypass the aggregate
  • ✅ Somebody can articulate why this system justifies the overhead

17

Sources

Primary

  • Jeffrey Palermo — The Onion Architecture, parts 1–4 (2008; part 4, 2012) — the four tenets, the "not for small websites" scoping, and the "outer layers may call any inner layer" rule
  • Alistair Cockburn — Hexagonal Architecture / Ports and Adapters (2005)
  • Robert C. Martin — Clean Architecture (2012 post; 2017 book)
  • Eric Evans — Domain-Driven Design (2003) — aggregates, value objects, repositories
  • Martin Fowler — AnemicDomainModel (2003); Patterns of Enterprise Application Architecture (2002)
  • Jimmy Bogard — Vertical Slice Architecture (2018) — the critique of layered/onion/clean as monolithic and mock-heavy

Analysis and comparison

  • Herberto Graça — Onion Architecture, The Software Architecture Chronicles — the clearest account of Onion as Ports & Adapters plus internal DDD structure
  • Code Maze — What are the Differences Between Onion Architecture and Clean Architecture in .NET? (updated July 2026) — project-reference matrices for both
  • CodeOpinion (Derek Comartin) — Is Vertical Slice Architecture better than Clean Architecture or Ports and Adapters?
  • CSA — Architectures in Comparison: Onion or Vertical Slice? (Oct 2025)
  • Rico Fritzsche — Why Vertical Slices Won't Evolve from Clean Architecture (2025)
  • Jon P Smith (The Reformed Programmer) — Is the repository pattern useful with Entity Framework Core? — the performance and over-genericity critique

Tooling and platform

  • Microsoft Learn — EF Core releases and planning; What's new in .NET 10
  • dotnet/core releases: .NET 10 is the current LTS (Nov 2025, supported to Nov 2028); .NET 11 STS lands Nov 2026
  • BenMorris/NetArchTest — fluent architecture rules for .NET
  • ArchUnitNET — the .NET port of ArchUnit; supports declared architecture models and custom conditions
  • Testcontainers for .NET — real-database integration testing

Compiled August 2026. Verify framework version details against current Microsoft documentation before adopting — .NET 11 reaches GA in November 2026 and will change the LTS/STS picture.