Onion and Clean Architecture
TheYard is a used-vehicle auction platform built in the open: a .NET 11 API, a React front end and
two databases underneath it. Its server is built as an onion. This page says what that pattern
means, where it came from, and how TheYard applies it ring by ring, project by project. Two other
pages carry the rest: Onion architecture, the practices
walks one bid through the rings with whole files you can copy, and
ADR: Onion and SOLID, how this codebase holds them
is the record of the decision, with the ten rules the build runs. This page is the one to read first.
In plain words
Imagine the code as rings, one inside another. The auction's rules sit in the middle. The code that
carries out what a visitor asks for wraps the rules. The database code and the web endpoints sit on
the outside. One rule holds it together: code may use the rings inside it and never the ones outside
it. So the rules in the middle know nothing about SQL Server, Cosmos DB or HTTP, and they can be
tested in milliseconds with no database running.
What that is worth: a developer can swap the database, the web framework or the hosting without
touching the auction's rules, and a new engineer can find any rule by asking which ring it belongs
to. The organization gets rules that are tested on every push without a database, and a shape the
build defends instead of one that depends on a reviewer noticing.
The words this page uses
- Ring: one layer of the code. In TheYard each inner ring is its own .NET project.
- Dependency: code in one place using a type from another, through a project reference, a
using line, or a call inside a method body.
- The Dependency Rule: dependencies point inward. Robert C. Martin's name for the one rule
every version of this pattern shares.
- Domain: the rules of the business, here the auction's: who may bid, how much, and when.
- Use case: one thing a visitor does, such as placing a bid, written as a method that runs the
rules and the stores in the right order.
- Port: an interface the inner code declares for something it needs from outside, such as a
place to keep bids.
- Adapter: a class in an outer ring that implements a port against one real thing, such as SQL
Server or Cosmos DB.
- Host: the web application itself: the endpoints that read a request and write the answer.
- Composition root: the one place, at startup, where the real classes are created and handed to
the code that needs them.
- BCL: the .NET base class library, the
System namespaces every .NET program has.
What it means
Three names, one rule. The pattern has been described three times under three names, and all three
agree on the sentence that matters.
- Hexagonal architecture, or ports and adapters (Alistair Cockburn, 2005). The application
should be driven equally well by a person, a test, a script or another program, and developed and
tested apart from its databases and devices. The application declares ports, the interfaces it
offers and the interfaces it needs, and adapters plug the real world into them.
- Onion architecture (Jeffrey Palermo, 2008). The same idea drawn as rings: the domain model at
the centre, domain services around it, application services around those, and the user interface,
the infrastructure and the tests in the outermost ring. Code may depend on rings more central than
itself and never on rings further out.
- Clean architecture (Robert C. Martin, 2012). Entities at the centre, then use cases, then
interface adapters, then frameworks and drivers, and one rule, the Dependency Rule: source code
dependencies point only inward.
What each ring holds, in the textbook:
What you get for building this way:
- Rules tested alone. The centre has no database, no network and no clock of its own, so a test
can run a thousand rule checks in the time one database query takes.
- Seams. A database, a framework or a hosting platform is replaced at a port, and the rings
inside the port do not change.
- A shape the compiler helps defend. When rings are projects, a project reference that would
point outward makes a cycle, and the compiler refuses it.
- A map. A new engineer who knows the rings knows where a rule lives before opening a file.
What it costs: more projects and more interfaces, and a bid passes through more hands on its way
to the database. The rings pay that back only when there is something to protect. When there is
not, the record says so under
When not to build it this way:
a small service over one table, a spike, or a script is clearer flat.
How it applies to TheYard
The textbook rings and TheYard's projects, side by side. Each textbook ring is one project here,
with one deliberate difference: the centre is split in two, because a ring with no behaviour at all
is a ring nothing can hide in.

A preview. Open the drawing in a new page to zoom in and follow the tie lines.
The arrows are project references
Each inward arrow in the drawing is one ProjectReference line in a project file, which is why the
compiler helps hold the shape: a reference pointing the wrong way would close a cycle, and the build
refuses it. The four project files, read from the running build:
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\TheYard.Data\TheYard.Data.csproj" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<CheckForOverflowUnderflow>true</CheckForOverflowUnderflow>
</PropertyGroup>
</Project>
Live from api/TheYard.Domain/TheYard.Domain.csproj, region *, read from this build at 99df7a8.
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\TheYard.Domain\TheYard.Domain.csproj" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
Live from api/TheYard.Application/TheYard.Application.csproj, region *, read from this build at 99df7a8.
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\TheYard.Application\TheYard.Application.csproj" />
<ProjectReference Include="..\TheYard.Infrastructure\TheYard.Infrastructure.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.64.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
<PackageReference Include="Azure.Identity" Version="1.18.0" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
Live from api/TheYard.Infrastructure.Cosmos/TheYard.Infrastructure.Cosmos.csproj, region *, read from this build at 99df7a8.
<Project Sdk="Microsoft.NET.Sdk.Web">
<ItemGroup>
<PackageReference Include="Azure.Communication.Email" Version="1.1.0" />
<PackageReference Include="Azure.Monitor.OpenTelemetry.AspNetCore" Version="1.6.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="11.0.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="11.0.0" />
<PackageReference Include="Scalar.AspNetCore" Version="3.4.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="11.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TheYard.Application\TheYard.Application.csproj" />
<ProjectReference Include="..\TheYard.Infrastructure\TheYard.Infrastructure.csproj" />
<ProjectReference Include="..\TheYard.Infrastructure.Cosmos\TheYard.Infrastructure.Cosmos.csproj" />
<ProjectReference Include="..\TheYard.Migrations.Sqlite\TheYard.Migrations.Sqlite.csproj" />
<ProjectReference Include="..\..\samples\theshed\TestProject.csproj" />
</ItemGroup>
<ItemGroup>
<Using Include="TheYard.Api.Shared.Activity" />
<Using Include="TheYard.Api.Shared.Auth" />
<Using Include="TheYard.Api.Shared.CostReadings" />
<Using Include="TheYard.Api.Shared.Documentation" />
<Using Include="TheYard.Api.Shared.Edge" />
<Using Include="TheYard.Api.Shared.Grades" />
<Using Include="TheYard.Api.Shared.Hosted" />
<Using Include="TheYard.Api.Shared.Instance" />
<Using Include="TheYard.Api.Shared.MachineReadings" />
<Using Include="TheYard.Api.Shared.Observability" />
<Using Include="TheYard.Api.Shared.PlanReadings" />
<Using Include="TheYard.Api.Shared.Proof" />
<Using Include="TheYard.Api.Shared.Resources" />
<Using Include="TheYard.Api.Shared.Sites" />
<Using Include="TheYard.Api.Shared.Stores" />
<Using Include="TheYard.Api.Shared.Usage" />
<Using Include="TheYard.Api.Shared.Wire" />
<Using Include="TheYard.Api.Shared.Wiring" />
<Using Include="TheYard.Infrastructure.Shared.Http" />
<Using Include="TheYard.Application.Features.Accounts" />
<Using Include="TheYard.Application.Features.Admin.Operations" />
<Using Include="TheYard.Application.Shared.Auction" />
<Using Include="TheYard.Application.Shared.Caching" />
<Using Include="TheYard.Application.Shared.Cards" />
<Using Include="TheYard.Application.Shared.Claude" />
<Using Include="TheYard.Application.Shared.History" />
<Using Include="TheYard.Application.Shared.Stores" />
<Using Include="TheYard.Domain.Features.Admin" />
<Using Include="TheYard.Domain.Features.Blog" />
<Using Include="TheYard.Domain.Shared.Visitors" />
<Using Include="TheYard.Domain.Shared.Auction" />
<Using Include="TheYard.Domain.Shared.Cards" />
<Using Include="TheYard.Domain.Shared.Usage" />
<Using Include="TheYard.Domain.Shared.Numbers" />
<Using Include="TheYard.Infrastructure.Cosmos.Features.Accounts" />
<Using Include="TheYard.Infrastructure.Cosmos.Features.Admin" />
<Using Include="TheYard.Infrastructure.Cosmos.Features.Links" />
<Using Include="TheYard.Infrastructure.Cosmos.Shared.Auction" />
<Using Include="TheYard.Infrastructure.Cosmos.Shared.History" />
<Using Include="TheYard.Infrastructure.Cosmos.Shared.Stores" />
<Using Include="TheYard.Infrastructure.Features.Admin.Cloud" />
<Using Include="TheYard.Infrastructure.Shared.Auction" />
<Using Include="TheYard.Infrastructure.Shared.History" />
<Using Include="TheYard.Infrastructure.Shared.Stores" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup>
<TieredCompilation>true</TieredCompilation>
<TieredPGO>true</TieredPGO>
<ServerGarbageCollection>false</ServerGarbageCollection>
<ConcurrentGarbageCollection>true</ConcurrentGarbageCollection>
</PropertyGroup>
<Target Name="LeaveTheShedsFilesToItsOwnFolder" AfterTargets="GetCopyToPublishDirectoryItems">
<PropertyGroup>
<TheShedFolder>$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)../../samples/theshed/'))</TheShedFolder>
</PropertyGroup>
<ItemGroup>
<_SourceItemsToCopyToPublishDirectory Remove="@(_SourceItemsToCopyToPublishDirectory)" Condition="$([System.String]::Copy('%(FullPath)').StartsWith('$(TheShedFolder)', StringComparison.OrdinalIgnoreCase))" />
<_SourceItemsToCopyToPublishDirectoryAlways Remove="@(_SourceItemsToCopyToPublishDirectoryAlways)" Condition="$([System.String]::Copy('%(FullPath)').StartsWith('$(TheShedFolder)', StringComparison.OrdinalIgnoreCase))" />
<_SourceItemsToCopyToPublishDirectoryIfDifferent Remove="@(_SourceItemsToCopyToPublishDirectoryIfDifferent)" Condition="$([System.String]::Copy('%(FullPath)').StartsWith('$(TheShedFolder)', StringComparison.OrdinalIgnoreCase))" />
</ItemGroup>
</Target>
</Project>
Live from api/TheYard.Api/TheYard.Api.csproj, region *, read from this build at 99df7a8.
Notice what is missing from the first two: no Entity Framework, no Cosmos DB SDK, no ASP.NET. The
rules and the use cases compile against the base class library and each other, and nothing else.
The ports are declared on the inside
Application needs to save a bid, and the database is outside it. So Application declares the
interface it needs, in its own words, and each adapter implements it. At compile time every arrow
still points inward, at the interface. The auction's ports, read from the running build:
public interface IVehicleSource
{
Task<IReadOnlyList<Vehicle>> LoadAsync(CancellationToken cancellation);
}
public interface IPhotoManifestSource
{
Task<IReadOnlyList<PhotoEntry>> LoadAsync(CancellationToken cancellation);
}
public interface IBidStore
{
Task<IReadOnlyList<StoredBid>> LoadAsync(CancellationToken cancellation);
Task<IReadOnlyList<StoredStanding>> LoadStandingsAsync(CancellationToken cancellation);
Task<StoredStanding?> ReadStandingAsync(string vehicleId, CancellationToken cancellation);
Task<IReadOnlyList<StoredBid>> BidsOnAsync(string vehicleId, CancellationToken cancellation);
Task<bool> TrySaveAsync(string userId, string vehicleId, BidState state, VehicleStanding standing, string? expectedVersion, CancellationToken cancellation);
Task ClearAsync(string userId, CancellationToken cancellation);
}
public interface IVehicleCatalogue
{
int Target { get; }
CatalogueFillPace Pace { get; }
Task<int> FilledAsync(CancellationToken cancellation);
Task FillAsync(IReadOnlyList<CatalogueEntry> batch, CancellationToken cancellation);
Task<SegmentCounts> CountAsync(CatalogueFilter filter, CancellationToken cancellation);
Task<IReadOnlyList<CatalogueEntry>> PageAsync(CatalogueFilter filter, CatalogueOrder order, int skip, int take, CancellationToken cancellation);
Task<IReadOnlyList<CatalogueEntry>> FindAsync(IReadOnlyCollection<string> ids, CancellationToken cancellation);
Task<InventoryFacets> FacetsAsync(CancellationToken cancellation);
}
Live from api/TheYard.Application/Shared/Auction/Ports.cs, region ports, read from this build at 99df7a8.
The names say what the inner ring needs (IBidStore) and nothing about the technology that answers
(ISqlBidRepository would leak it). The two adapters that implement them, and the one place that
decides which adapter a store gets, are shown whole on the practices page under
The inner ring owns the interface.
One bid, through the rings
A signed-in buyer bids on a vehicle. The endpoint reads the request and asks PlaceBidHandler,
which reads the vehicle as it stands through StandingReader and hands the bid to BidBook, which
asks BidRules whether it stands; the rules answer with a BidOutcome and never touch a database;
on yes, BidBook saves through IBidStore and only
then records the bid; whichever adapter was wired in at startup writes the row or the document; the
endpoint writes the answer. Nothing in the host decides anything, and nothing in the rules knows
which store it is talking to.

A preview. Open the bid's walk in a new page to zoom in and follow it.
The seven steps, with the four files the bid passes through shown whole, are on the practices page
under A request walks the rings.
The front end keeps the same shape
src/ is drawn in the same direction. Components use hooks, hooks use src/lib, and src/lib
imports nothing from React, so the logic that formats a price or reads the address bar can be
tested with no component rendered. Every file in src/app and src/library opens with a header
that says what it does, what it does not, and who uses it, and a test reads the header back against
the real importers
(ADR: The React configuration, explained).
What holds the shape
A rule held by code review alone slips the first busy week. TheYard's rings are held by ten tests
that read the compiled assemblies with NetArchTest, so a dependency hidden inside a lambda or an
async method fails the build as surely as a using line would. The six rules for the rings, read
from the running build:
private const string BaseClassLibrary = "System";
private const string CoverageTracker = "Coverlet.Core.Instrumentation";
private static readonly string[] TheDiskAndTheNetwork =
[
"System.IO.File", "System.IO.Directory", "System.IO.FileStream", "System.IO.StreamReader", "System.IO.StreamWriter",
"System.IO.FileInfo", "System.IO.DirectoryInfo", "System.IO.FileSystemInfo", "System.IO.Compression", "System.IO.MemoryMappedFiles", "System.IO.Pipes",
"System.Net", "System.Data",
];
private static readonly string[] TheMachine = ["System.Random", "System.TimeProvider", "System.Environment", "System.Diagnostics.Stopwatch", "System.Diagnostics.Process"];
[Fact]
public void Data_depends_on_nothing_outside_the_BCL()
{
var result = InRing(typeof(Vehicle), "TheYard.Data")
.ShouldNot().HaveDependencyOtherThan(BaseClassLibrary, CoverageTracker, "TheYard.Data")
.GetResult();
Assert.True(result.IsSuccessful, Explain(result));
var reaches = InRing(typeof(Vehicle), "TheYard.Data").ShouldNot().HaveDependencyOnAny([.. TheDiskAndTheNetwork, .. TheMachine]).GetResult();
Assert.True(reaches.IsSuccessful, Explain(reaches));
Assert.Empty(TypeLookups(typeof(Vehicle).Assembly.Location, "TheYard.Data"));
}
[Fact]
public void Data_has_no_behaviour()
{
Assert.Empty(Behaviour(typeof(Vehicle).Assembly.Location));
}
[Fact]
public void Domain_depends_on_nothing_outside_the_BCL_and_Data()
{
var result = InRing(typeof(BidRules), "TheYard.Domain")
.ShouldNot().HaveDependencyOtherThan(BaseClassLibrary, CoverageTracker, "TheYard.Data", "TheYard.Domain")
.GetResult();
Assert.True(result.IsSuccessful, Explain(result));
}
[Fact]
public void Application_depends_only_on_Domain_Data_and_the_BCL()
{
var result = InRing(typeof(StandingReader), "TheYard.Application")
.ShouldNot().HaveDependencyOtherThan(BaseClassLibrary, CoverageTracker, "TheYard.Data", "TheYard.Domain", "TheYard.Application")
.GetResult();
Assert.True(result.IsSuccessful, Explain(result));
}
[Fact]
public void Domain_never_reaches_the_disk_the_network_or_the_clock()
{
var result = InRing(typeof(BidRules), "TheYard.Domain")
.ShouldNot().HaveDependencyOnAny([.. TheDiskAndTheNetwork, .. TheMachine])
.GetResult();
Assert.True(result.IsSuccessful, Explain(result));
Assert.Empty(ClockReads(typeof(BidRules).Assembly.Location, "TheYard.Domain"));
Assert.Empty(TypeLookups(typeof(BidRules).Assembly.Location, "TheYard.Domain"));
}
[Fact]
public void Application_never_reaches_the_disk_or_the_network()
{
var result = InRing(typeof(StandingReader), "TheYard.Application")
.ShouldNot().HaveDependencyOnAny(TheDiskAndTheNetwork)
.GetResult();
Assert.True(result.IsSuccessful, Explain(result));
}
[Fact]
public void The_document_store_adapter_borrows_only_the_shared_user_from_the_relational_one()
{
string[] relational = typeof(YardDbContext).Assembly.GetTypes()
.Where(type => type.IsPublic && type != typeof(YardUser))
.Select(type => type.FullName!)
.Append("Microsoft.EntityFrameworkCore")
.Append("Microsoft.AspNetCore.Identity.EntityFrameworkCore")
.Append("Microsoft.Data")
.ToArray();
var result = Types.InAssembly(typeof(CosmosStore).Assembly)
.ShouldNot().HaveDependencyOnAny(relational)
.GetResult();
Assert.True(result.IsSuccessful, Explain(result));
}
[Fact]
public void Infrastructure_adapts_and_decides_nothing()
{
var found = new List<string>();
foreach (var adapter in new[] { typeof(YardDbContext).Assembly, typeof(CosmosStore).Assembly })
{
using var module = ModuleDefinition.ReadModule(adapter.Location);
found.AddRange(module.GetTypeReferences()
.Where(reference => reference.Namespace.StartsWith("Microsoft.AspNetCore", StringComparison.Ordinal) && !reference.Namespace.StartsWith("Microsoft.AspNetCore.Identity", StringComparison.Ordinal))
.Select(reference => $"{adapter.GetName().Name} uses {reference.FullName}"));
found.AddRange(MoneyDecisions(module));
}
Assert.True(found.Count == 0, string.Join(Environment.NewLine, found.Distinct()));
}
Live from api/TheYard.Tests/OnionTests.cs, region rings, read from this build at 99df7a8.
The four rules for the host, what each of the ten stops, and which four failed against the code
the day they were written are in the record, under
How the build holds them.
- Architecture tests
- 19
- Files with the header
- 164 of 164
Numbers read from the build when the page is opened.
References
- Alistair Cockburn, Hexagonal architecture
(2005): the original ports and adapters article, and the intent this page opens on, an
application driven equally by people, tests and other programs.
- Jeffrey Palermo, The Onion Architecture: part 1
(2008): the rings, and the case for putting interfaces in the core.
- Robert C. Martin, The Clean Architecture
(2012): the Dependency Rule, and the four rings this page's table follows.
- Common web application architectures, .NET architecture guides:
Microsoft's description of clean architecture in .NET, with abstractions in the core and
implementations in the infrastructure layer.