Skip to content

Onion and Clean Architecture

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:

Ring, innermost first What lives there Why it sits where it does
Entities, the domain model The business rules that would exist with no software at all. Changes least, and nothing it needs lives outside.
Use cases, the application What the software does with those rules, in order, and the ports it needs. Depends on the rules, and on nothing about how they are stored or shown.
Interface adapters Translators: controllers that read requests, gateways and repositories that talk to a database. Each knows one real thing, and the rings inside it know none of them.
Frameworks and drivers The web framework, the database engine, the browser. The parts most likely to be replaced, kept furthest from the rules.

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.

Palermo's onion beside TheYard's rings: each textbook ring tied to the project that is that ring, every dependency pointing inward

A preview. Open the drawing in a new page to zoom in and follow the tie lines.

Textbook ring TheYard project What lives there May use
The domain model api/TheYard.Data Vehicle and PhotoEntry, exactly as the dataset has them. Records with no behaviour. the BCL only
Domain services, the rules api/TheYard.Domain BidRules, AuctionSchedule, AuctionClock, StandingRules, VehicleFilter, VehicleOrdering, VehicleSearchIndex, PhotoGallery, and the Fnv1a hash the schedule is derived from. Pure functions of their inputs and the clock they are handed. Data
Application services, the use cases api/TheYard.Application One handler per request, each a query or a command (ADR-115); the auction's three parts, Stock, BidBook and Room, each behind a reading and a writing interface, and StandingReader, which every query reads a vehicle through; the auction's ports and the operator's ports. Domain, Data
Infrastructure, the adapters api/TheYard.Infrastructure and api/TheYard.Infrastructure.Cosmos The same ports implemented twice: EF Core over Azure SQL Database or SQLite, and the Cosmos DB SDK. Application; the document store adapter also borrows one shared user type from the relational one
User interface and host api/TheYard.Api, with src/ and render/ Endpoints that read a request, ask their one handler and write the answer; the composition root in Composition/; the React front end and the service that draws it on the server, both clients of the API. Application and both adapters; the front end, the wire only
Tests api/TheYard.Tests Rules with fixed clocks, use cases with hand-written fakes at the ports, the real host through WebApplicationFactory, and the ten tests that hold the rings. everything

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>
    <!-- Arithmetic on money throws rather than wrapping: a price that wrapped to a negative number
         would be a minimum next bid a buyer could pass with a dollar. -->
    <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" />
    <!-- For YardUser, the one type the two stores share: an account is the
         same thing whichever store holds it, and OnionTests allows that type
         and nothing else from here (ADR: Onion and SOLID, how this codebase
         holds them). -->
    <ProjectReference Include="..\TheYard.Infrastructure\TheYard.Infrastructure.csproj" />
  </ItemGroup>

  <ItemGroup>
    <!-- The SDK directly rather than the EF Core provider, because every
         response carries the request charge and the diagnostics this lane
         exists to show, and the provider surfaces neither
         (ADR: A second store on Cosmos DB, and what it costs). -->
    <PackageReference Include="Microsoft.Azure.Cosmos" Version="3.64.0" />
    <!-- The SDK insists on an explicit reference to its own serializer even
         when, as here, the documents go through System.Text.Json. 13.0.4 is
         the version already in this application's dependency graph. -->
    <PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
    <!-- The container's managed identity, or the developer's signed-in Azure
         CLI session. No key exists on the account to fall back to.

         Pinned, not the newest: SqlClient takes its managed identity token
         through the same library, and 1.21.0 took longer than SqlClient's
         thirty seconds to find the identity endpoint, so the SQL connection was
         cancelled and the site served from files. Pinned at 1.18.0, the floor
         of the sign-in package SqlClient 7 needs, from EF Core 11 on; it moves
         only with a live read that the site is on Azure SQL Database.
         PackagePinTests holds the pin (ADR: A second store on Cosmos DB, and
         what it costs, addendum; ADR: Moving to .NET 11 in four ships). -->
    <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>
    <!-- The one email this site sends, the password reset link, as the
         containers' own identity (ADR: Accounts and per-user bids, addendum).
         The Azure.Core this project resolves carries its own copy of the
         credential types the pinned Azure.Identity has, and naming one here
         is ambiguous to the compiler, so the credential is built in the
         Cosmos DB project against the pinned library and handed over as a
         TokenCredential; no credential type is named in this project. -->
    <PackageReference Include="Azure.Communication.Email" Version="1.1.0" />
    <!-- Azure Monitor's OpenTelemetry distro: requests, dependencies and
         exceptions to Application Insights with one call in Program.cs, and
         nothing at all when the connection string is absent (ADR-024). -->
    <PackageReference Include="Azure.Monitor.OpenTelemetry.AspNetCore" Version="1.6.0" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="11.0.0" />
    <!-- The API's description of itself: the framework's own OpenAPI generator,
         which reads the routing table and the typed results, and Scalar for the
         page a person opens at /api/reference. Both pinned; the generator to
         the same servicing line as the rest of ASP.NET Core here, Scalar to the
         version its bundled assets were read on (ADR: The API describes itself). -->
    <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" />
    <!-- The second store, chosen at startup by the presence of an account
         endpoint (ADR: A second store on Cosmos DB, and what it costs). -->
    <ProjectReference Include="..\TheYard.Infrastructure.Cosmos\TheYard.Infrastructure.Cosmos.csproj" />
    <!-- Referenced so the assembly lands beside the host: EF resolves a
         migrations assembly by name at run time, and a name that is not loaded
         is a migration that does not exist. Only SQLite has migrations; the SQL
         Server schema is the SQL project (ADR: Data first, and the database in
         source control). -->
    <ProjectReference Include="..\TheYard.Migrations.Sqlite\TheYard.Migrations.Sqlite.csproj" />
    <!-- The Shed, the getting-started sample beside this app, served by this process under its own
         name since 19 October (Composition/ShedMount.cs; ADR: One web app for every .NET process).
         Referenced for its assembly only: its documents, sample home and page are published to a
         folder of their own by the Dockerfile and read from there, so none of its files is copied
         beside this app's, where its appsettings.json and README.md would collide with these. -->
    <ProjectReference Include="..\..\samples\theshed\TestProject.csproj" />
  </ItemGroup>

  <!-- #region shared-concerns -->
  <!-- The host's shared code, one namespace per concern under Shared/ (ADR-114: The host root holds one file). Every
       file in the host may use a shared concern, so each is imported once here rather than in every file that names
       one; no slice of the host is imported, because a host slice reaching another is what SliceTests rule 1 forbids.
       The inner rings' slices below are imported because the host composes them: its wiring builds their handlers
       and adapters, which is the one place a slice is reached from outside its folder. -->
  <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>
  <!-- #endregion shared-concerns -->

  <PropertyGroup>
    <TargetFramework>net11.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <!-- #region runtime-settings -->
  <!-- How the runtime compiles and collects this process (ADR: Compiled before it ships). Written out even where they
       are the defaults, so the choice is read here and held by CompilationTests rather than inherited silently.
       ReadyToRun itself is a publish switch, in the Dockerfile, so a developer's build and the tests are unchanged. -->
  <PropertyGroup>
    <!-- Tiered compilation with profile-guided optimization: code compiled ahead of time runs first, and the methods
         that turn out hot are compiled again at full optimization with what the first runs measured. -->
    <TieredCompilation>true</TieredCompilation>
    <TieredPGO>true</TieredPGO>
    <!-- Workstation collection, background collection on. The web SDK's default is server collection, which keeps a
         heap per core and holds more memory for throughput; on a plan whose memory is the scarcest thing it has, and
         whose one core leaves server collection little to work with, the smaller footprint is the better trade.
         /api/admin/metrics says which mode the live process runs. -->
    <ServerGarbageCollection>false</ServerGarbageCollection>
    <ConcurrentGarbageCollection>true</ConcurrentGarbageCollection>
  </PropertyGroup>
  <!-- #endregion runtime-settings -->

  <!-- #region shed-files -->
  <!-- The Shed's documents, sample home, page and appsettings.json would be published beside this app's, where its
       appsettings.json and README.md have the same names as this app's and the publish stops (NETSDK1152). They are
       The Shed's, published by the Dockerfile to a folder of its own that Shed__ContentRoot names, so they are left
       out of this publish: only The Shed's assembly comes here, through the project reference. -->
  <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>
  <!-- #endregion shed-files -->

</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:

// The three seams the layers meet at. Application declares what it needs and
// never learns where the data lives; Infrastructure implements these against
// EF Core and SQLite, against Cosmos DB, the tests against in-memory arrays,
// and the 100,000-record scale-up is a decorator over IVehicleSource that
// nothing above it can see.
//
// Every member returns a Task, because the document store has no synchronous
// driver, and a port that held a request thread while a cloud store answered
// would stall a one-vCPU container (ADR: The ports learn to wait). Every member
// also takes a CancellationToken, because a read the visitor walked away from is
// work the site pays for twice, and a path that drops the token cannot be made to
// stop later without changing every caller (the same record, the addendum on the
// token). Taking it is not the same as cancelling: a bid write that has entered
// the gate runs to its end, and the two startup loads take the host's stopping
// token rather than any request's.
/// <summary>Port: where the vehicle dataset comes from.</summary>
public interface IVehicleSource
{
    Task<IReadOnlyList<Vehicle>> LoadAsync(CancellationToken cancellation);
}

/// <summary>Port: where the photo manifest comes from.</summary>
public interface IPhotoManifestSource
{
    Task<IReadOnlyList<PhotoEntry>> LoadAsync(CancellationToken cancellation);
}

/// <summary>
/// Port: where everybody's bids are kept, and the one place each vehicle's
/// standing is decided. Two sites run one image over the same store, so the
/// standing (price, count, high bidder, sold) is a row or document the store
/// owns, written with a compare-and-set on its version. Memory is a cache of
/// it, and a cache can be stale; the store cannot be argued with
/// (ADR: Three readers with no memory of the project, item 5).
/// A bid belongs to a user (ADR: Accounts and per-user bids), so a buyer's row
/// is keyed by the pair and the standing by the vehicle.
/// </summary>
public interface IBidStore
{
    /// <summary>Every buyer's row, for the replay at startup.</summary>
    Task<IReadOnlyList<StoredBid>> LoadAsync(CancellationToken cancellation);

    /// <summary>Every vehicle's stored standing, for the replay at startup.</summary>
    Task<IReadOnlyList<StoredStanding>> LoadStandingsAsync(CancellationToken cancellation);

    /// <summary>One vehicle's stored standing and its version, or null when the store holds none for it.</summary>
    Task<StoredStanding?> ReadStandingAsync(string vehicleId, CancellationToken cancellation);

    /// <summary>
    /// Every buyer's row on one vehicle. Read when the store holds no standing
    /// for it, which is a vehicle bid on before standings existed or one a
    /// reset cleared, so the standing is worked out from the rows rather than
    /// taken to be the opening ask.
    /// </summary>
    Task<IReadOnlyList<StoredBid>> BidsOnAsync(string vehicleId, CancellationToken cancellation);

    /// <summary>
    /// Writes the buyer's row and the vehicle's new standing, but only if the
    /// standing still carries <paramref name="expectedVersion"/>; null expects
    /// there to be no standing yet. False means another writer moved it first,
    /// and nothing of this bid was kept: the caller reads again and runs the
    /// rules again.
    /// </summary>
    Task<bool> TrySaveAsync(string userId, string vehicleId, BidState state, VehicleStanding standing, string? expectedVersion, CancellationToken cancellation);

    /// <summary>
    /// Forget one person's bids, and the standing of every vehicle they bid on,
    /// so the next read works each one out again from whoever is left. Not
    /// everybody's: this is what the reset button on a page a stranger can also
    /// be looking at is allowed to do (ADR: Reset is one person's start-over).
    /// </summary>
    Task ClearAsync(string userId, CancellationToken cancellation);
}

/// <summary>
/// Port: the catalogue as the store holds it, all hundred thousand vehicles with
/// the slot each id's hash gives it, and the store doing the filtering, the
/// ordering and the paging (ADR: The store does the work). Application plans a
/// listing out of these primitives, the three schedule segments, the room's and
/// the bids' overlay, the page, and the adapters only translate a filter and an
/// order into their own query: EF Core over the Catalogue table, the SDK over the
/// catalogue container. Every read is bounded by the page it asks for; nothing
/// here hands back the whole catalogue.
/// </summary>
public interface IVehicleCatalogue
{
    /// <summary>How many vehicles this catalogue is the first of: the expansion's target count.</summary>
    int Target { get; }

    /// <summary>How the store wants to be filled: a batch at a time, a pause between, and up to how many it fills at warm-up.</summary>
    CatalogueFillPace Pace { get; }

    /// <summary>How many of the first <see cref="Target"/> vehicles the store holds with their slot, read as one count.</summary>
    Task<int> FilledAsync(CancellationToken cancellation);

    /// <summary>Writes one batch of the expansion, each vehicle at its place; a vehicle already there is left as it is or rewritten the same.</summary>
    Task FillAsync(IReadOnlyList<CatalogueEntry> batch, CancellationToken cancellation);

    /// <summary>How many vehicles match, split by the three schedule segments, in one read where the store allows it.</summary>
    Task<SegmentCounts> CountAsync(CatalogueFilter filter, CancellationToken cancellation);

    /// <summary>One page of the matches in one order, skipped and taken in the store's own query.</summary>
    Task<IReadOnlyList<CatalogueEntry>> PageAsync(CatalogueFilter filter, CatalogueOrder order, int skip, int take, CancellationToken cancellation);

    /// <summary>The vehicles with these ids, by point read where the address names the partition; an id the catalogue lacks is simply absent.</summary>
    Task<IReadOnlyList<CatalogueEntry>> FindAsync(IReadOnlyCollection<string> ids, CancellationToken cancellation);

    /// <summary>The distinct values behind the filters, read once at warm-up.</summary>
    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.

One bid through TheYard's rings: the endpoint asks Application, Application asks Domain, Domain decides, Application saves through the IBidStore port, an adapter writes the store, and the endpoint answers

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:

/// <summary>The namespaces every ring may use: the .NET base class library and nothing else.</summary>
private const string BaseClassLibrary = "System";

/// <summary>
/// The tracker the coverage collector writes into every assembly it measures. CI runs these
/// tests with coverage on, so without this the rings would fail on code nobody wrote.
/// </summary>
private const string CoverageTracker = "Coverlet.Core.Instrumentation";

/// <summary>
/// The parts of the base class library that reach the disk, the network or a database. The
/// rules above allow the whole library, so these are held out of the inner rings by name.
/// </summary>
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",
];

/// <summary>What a rule that takes everything it needs as a value never reads for itself: a clock, a process, a type found by its name.</summary>
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));
    // System is allowed whole, so the disk, the network and the machine are held out by name.
    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()
{
    // Pure records (CLAUDE.md): a property, a constructor, what the compiler writes for a record,
    // and nothing else. A computed rule in Data is a second Domain nobody tests as one.
    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()
{
    // A rule is a function of what it is handed: the vehicle, the bids and the clock. Reading
    // the time, a random number or a file itself would make it untestable with a fixed 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()
{
    // A use case reaches a store or a service through a port; the disk and the network belong
    // to the adapters behind those ports.
    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()
{
    // Identity's user entity is the one type both stores keep accounts as. Anything else from
    // the relational adapter, and Entity Framework above all, stays on its own side.
    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()
{
    // An adapter turns a port's call into a store's and back. The web (beyond Identity's user
    // store) is the host's, and a rule about money is the Domain's: an adapter method that takes a
    // price or a bid by name and compares it, or reads a vehicle's price and compares it, is a
    // second copy of BidRules that no Domain test sees.
    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

Store

The Yard, home

Steven StoutStaff .NET engineerRemote

Production .NET that stays up. Built with AI, measured on every version.

Steven Stout

Hi, I'm Steve. I build the systems that make delivery boring in the best way, then coach people inside them.

  • 200+

    production releases, none took the platform down

    Conway Investment Research, 2019 to 2024. Sole engineer for the first three years on a live financial advisory platform.

    See how
  • 50%

    shorter release cycle

    Storee Construction, 2024 to 2026. Four ASP.NET applications onto one .NET 10 platform on Azure, with a four-person team I hired and mentored.

    See how

01Verified

Steven Stout

A real person, and the work is mine.

  • Identity

    Checked by LinkedIn, not by me.

    LinkedIn verified my government ID.

  • Running system

    You are looking at it.

    Version 1.0.5.273 is live. Nothing ships unless it passes the automated gates first.

That's who I am. Here's how I work.

02Strengths

Ten strengths, each with the proof beside it. The numbers match my resume and LinkedIn, and the live ones are read from this site as you look.

  • 01

    Keeps production alive

    200+ releases on a live financial platform, and none took it down. Sole engineer for the first three years.

    See the Conway work

  • 02

    Simplifies messy systems

    Four ASP.NET applications onto one .NET 10 platform on Azure, and a release cycle 50% shorter.

    See the Storee work

  • 03

    Marries dev and infrastructure

    Blue-green releases at Storee that flipped in about 5 seconds with nobody signed out, and Azure Front Door at two employers.

    See this site's cloud

  • 04

    Designs data that holds up

    White-label clients on one shared database, the isolation built into the data, and no cross-client issues.

    See the Conway work

  • 05

    Keeps AI-written code honest

    15 quality numbers that may only improve: 273 releases in a row with none worse.

    See the quality numbers

  • 06

    Resourceful

    $30,000+ cut from Azure and vendor spend at Conway. This site's Azure bill is public, resource by resource.

    See the bill

  • 07

    Builds people up

    Hired and mentored a four-person team. 13 colleagues recommend me by name.

    Read the recommendations

  • 08

    Takes ideas to production

    This site: designed, built and run solo, with 352 versions measured through one gate.

    How it was built

  • 09

    Writes clearly

    Posts on real engineering problems, in plain words.

    Read the blog

  • 10

    Owns decisions

    153 decision records, each with its tradeoff and the call I made.

    See the decision records

Built with AI. Gated so quality never slides.

Steven Stout’s showcase: a used-vehicle auction on .NET and React, built and run by one engineer, live on Azure, with its decisions written down.

No quality number has gotten worse at any release since 1.0.5.1 on 10 November: 273 releases in a row.

One engineer, an AI agent and a gate that checks 15 quality numbers on every release. 352 versions measured, with every result public, the worst days included.

82 releases in the last 7 days, each through the same gate.

Async methods with no CancellationToken, may only fall

11091.0.3.1391.0.5.2731.0.4.115, the ratchet
Every number, on the Quality page

TheYard, right nowLive

Answering in

unread

02505007501,000

server time at p95, the usual five minutes of the last day.

Azure this month

unread

the bill, by resource, read from Azure. The Admin tab shows every line.

Since the last roll

unread

 

rolled in place by the pipeline, behind one gate.

People who have visited

unread

30 days agotoday

Scanners, my own tools' and my own reads left out.

03Start here

04Where teams are heading

How I see engineering with AI, and the setup on this site that backs it.

AI-augmented teams · Architecture and ownership

AI writes more of the code. Someone still has to own what ships.

Teams are going to be heavily AI-augmented. That moves the senior job toward architecture and technical ownership: deciding what to build in pieces small enough to verify, and owning what ships.

  • Task tracking will get automated too. Judgment stays human: seeing a design fail at scale before it does.
  • On this site the AI's first design held the whole catalogue in memory. I caught it when the App Service plan hit 82 per cent and moved the work to the store.

What the AI wrote, what I decided

07Tech stack

  •    
  •    
  •    

Read from the build, never typed by hand

What TheYard runs on

What we use, where it runs, its AWS twin, the version as built, and the file that proves it.

Cloud patterns, not one vendor: every Azure piece in this stack has a named AWS twin. Mapped, not yet run on AWS.

  • .NET 1114 projects
  • React 19.3TypeScript 7.0
  • Azure9 Bicep files
  • 11GitHub Actions workflows
The whole stack, with the file that proves each line

The last release the gate stopped was 1.0.5.258 on 2 December, at its browser 1 of 2 job.

08How it is built

09How it is run

10Who and why

Next step

11What has to work, where is it today, and what does success look like?

Book 20 minutes opens an email to me with those three questions in it, and I answer with a time.

Book 20 minutes

Your email app should have opened with this message. If it did not, copy it and send it from any mailbox.

Or message me on LinkedIn