Skip to content

SOLID Principles

SOLID Principles

SOLID is five principles for arranging code so that it can change without breaking. The rings on the Onion and Clean Architecture page rest on them. This page takes the five one at a time: what each one means in plain words, where it came from, and where it shows in TheYard, with the code read from the running build. The record behind the page is ADR: Onion and SOLID, how this codebase holds them, which also lists where a principle was deliberately not pushed further.

In plain words

Each letter of SOLID is one habit. The drawing takes them one at a time, with where TheYard shows each one.

The five SOLID letters one under the next, each with what it means in plain words and where TheYard shows it

A preview. Open the drawing in a new page to read it full size.

  • S, Single Responsibility. Each class has one job, so it has only one reason to change.
  • O, Open / Closed. Add new behaviour by writing new code, and leave the code that already works alone.
  • L, Liskov Substitution. Anything that stands in for something else has to behave the same way, so the code using it never notices the swap.
  • I, Interface Segregation. Keep interfaces small and shaped to the code that calls them, so no class has to depend on methods it never uses.
  • D, Dependency Inversion. Important code depends on contracts it owns, never on the database or the framework underneath it. The details plug into the contract, not the other way round.

Why it matters: code that follows them is easier to read and to fix, its parts lean on each other less, and each part can be tested on its own.

What that is worth: a developer can add a second database, a new endpoint or a new page without reopening code that already works, and the organization gets a codebase where a change lands in one place, is covered by the tests that already exist, and does not surprise the code around it.

The words this page uses

  • Principle: a rule of thumb about shape, not a law. Each one below says where TheYard stops applying it.
  • Responsibility: one reason for a piece of code to change, which usually means one group of people who would ask for the change.
  • Interface: in C#, a contract a class promises to keep: these methods, with these meanings.
  • Abstraction: an interface or a base type that says what is done without saying how.
  • Substitution: putting one implementation where another was, and nothing around it noticing.
  • Port and adapter: the interface the inner ring declares, and the class outside that implements it (the words are explained on the Onion and Clean Architecture page).
  • Composition root: the one place, at startup, where the real classes are created and wired.
  • Sealed: a C# class nothing can inherit from, so no derived type can change its meaning.

Where the five came from

Robert C. Martin collected the five in the second half of the 1990s, starting from a 1995 newsgroup post, and published them as the principles of object-oriented design; Michael Feathers later lined the letters up into the word SOLID. Two of the five are older than the collection: Bertrand Meyer stated the open-closed principle in 1988, and Barbara Liskov described the substitution idea in a 1987 keynote. The other three are Martin's own.

S, single responsibility

What it means. A class, or a file, has one reason to change. Martin's later restatement is the useful one: a reason to change is a group of people, so a module should answer to one group. When two groups can each force a change to the same file, their changes collide.

In TheYard. A rule lives in TheYard.Domain and nowhere else. BidRules decides whether a bid stands. StandingRules holds the one rule for raising a vehicle's shown price, and three callers (the buyer's bids, the room's bids and the room's price to beat) all raise a price through it, so the rule has one copy and the three cannot drift apart:

extension(Vehicle vehicle)
{
    /// <summary>
    /// The vehicle with a bid layered over it, and only when the bid is higher than the
    /// price it already shows. A lower bid leaves the vehicle as it was, so laying the
    /// buyer's bids and then the room's over the dataset always ends on the highest of the
    /// three. The bid count keeps the larger of the two counts, because both count the same
    /// auction from different sides.
    /// </summary>
    public Vehicle RaisedTo(int amount, int bidCount) =>
        amount > (vehicle.CurrentBid ?? 0)
            ? vehicle with { CurrentBid = amount, BidCount = Math.Max(vehicle.BidCount, bidCount) }
            : vehicle;

    /// <summary>Whether the reserve is met at the price this vehicle shows.</summary>
    public ReserveStatus Reserve => ReserveOf(vehicle.ReservePrice, vehicle.CurrentBid);
}

Live from api/TheYard.Domain/Shared/Auction/StandingRules.cs, region raised-to, read from this build at 99df7a8.

The host keeps the same discipline at the top. Program.cs is a table of contents: each line is one call, and the comment beside it names the file in Composition/ that holds the details, one file per job (the stores, the sessions, the activity counters, the API's shape, the Admin tab) (ADR: The composition root, split by job):

var builder = WebApplication.CreateBuilder(args);
var paths = HostPaths.Find(builder.Environment.ContentRootPath);                    // Shared/Wiring/HostPaths.cs
var build = new BuildInfo(builder.Configuration["APP_VERSION"] ?? "dev", builder.Configuration["APP_COMMIT"] ?? "local");
var identity = HostIdentity.From(builder.Configuration);                           // Shared/Instance/HostIdentity.cs
builder.Services.AddSingleton(paths);
builder.Services.AddSingleton(build);
builder.Services.AddSingleton(identity);

// None, said here rather than deep inside the registration: the lifetime that owns
// ApplicationStopping is made by Build() below, so nothing stops the stores being asked, and this
// is the one file where that is a true statement instead of a token somebody forgot to thread.
var stores = await builder.AddTheYardStoresAsync(paths, CancellationToken.None);   // Shared/Wiring/StoreRegistration.cs
builder.AddTheYardObservability(stores.Backends, stores.Document, stores.SqlLog, stores.StoreLog, stores.Accessor, stores.CurrentRequest);
builder.AddTheYardSessions();                                                      // Shared/Wiring/AuthRegistration.cs
builder.AddTheYardActivity(stores.Backends, stores.Document, stores.Relational);   // Shared/Wiring/ActivityRegistration.cs
builder.AddTheYardApi(build);                                                      // Shared/Wiring/ApiRegistration.cs
builder.AddTheYardTelemetry(identity);                                             // Shared/Wiring/TelemetryRegistration.cs
builder.AddTheYardAdmin(stores.Relational, build, identity);                       // Shared/Wiring/AdminRegistration.cs
builder.AddTheYardCosts(identity, stores.Relational);                              // Shared/Wiring/CostRegistration.cs
builder.AddTheYardUsage();                                                         // Shared/Wiring/UsageRegistration.cs

var modules = Modules.InThisHost();                                                // Shared/Wiring/Modules.cs, every Features/*/Module.cs
foreach (var module in modules)
{
    module.Register(builder.Services, builder.Configuration);
}
builder.AddTheYardStartup(identity);                                               // Shared/Wiring/StartupRegistration.cs
builder.AddTheYardHostedSites();                                                   // Shared/Wiring/HostedSiteRegistration.cs, last

var app = builder.Build();
await app.MountTheHostedSitesAsync(app.Lifetime.ApplicationStopping);  // Shared/Sites/HostedSiteMount.cs
app.UseTheYardRequestPipeline(paths, identity);                                    // Shared/Wiring/RequestPipeline.cs

Live from api/TheYard.Api/Program.cs, region composition, read from this build at 99df7a8.

The front end holds it as a rule the build reads. Every file in src/app and src/library opens with three lines, what it does, what it does not do and who uses it, and no file runs past three hundred lines. A file that has to is named in the test with the reason it is allowed, which keeps the reason where a reader of the rule will find it. The test reads the headers back, and checks "Used by" against the files that really import it:

/// <summary>The two folders the rule holds for code and stylesheets alike, relative to the repository root.</summary>
private static readonly string[] Folders = ["src/app", "src/library"];

/// <summary>What a file in them can be: code, and the stylesheets beside it.</summary>
private static readonly string[] Kinds = [".ts", ".tsx", ".css"];

/// <summary>And every stylesheet anywhere under this folder: a sheet grows a job at a time the way code does.</summary>
private const string Sheets = "src";

/// <summary>The three labels, in the order a header gives them.</summary>
private static readonly string[] Labels = ["Does:", "Does not:", "Used by:"];

/// <summary>
/// Past three hundred lines, each with why. One job per file keeps a file
/// short. The four component sheets named here each hold one
/// component's look, shared by that component and the parts split out of
/// it, and are over the line because the look is one piece; each comes
/// off this list when its sheet is split by job.
/// </summary>
private static readonly Dictionary<string, string> LongAllowed = new(StringComparer.Ordinal)
{
    ["src/components/landing/Landing/Landing.module.css"] = "the landing page's one look (hero, featured tiles, section tiles); split with Landing.tsx in the component split lane",
    ["src/components/layout/SideNav/SideNav.module.css"] = "the side rail's two shapes, one set of rows: one sheet shared by SideNav.tsx and the rows split out of it",
    ["src/components/admin/AdminPanel/AdminPanel.module.css"] = "the Admin workbench's frame: one sheet shared by AdminPanel.tsx and the parts split out of it",
    ["src/components/vehicle/VehicleDetail/VehicleDetail.module.css"] = "a vehicle's own page; split with VehicleDetail.tsx in the component split lane",
    ["src/styles/sales.css"] = "the sales pages' shared parts as one sheet, one region per part, as ADR: The sales pages set the site's look names it, so a page that takes the look reads one file",
};

Live from api/TheYard.Tests/FileHeaderTests.cs, region the-header-rule, read from this build at 99df7a8.

Where it stops. Program.cs lists twelve calls, one per area of the application, rather than twelve classes with one method each, because a list a reader can scan is the job. The record's section What is kept on purpose names the others.

O, open and closed

What it means. Code should be open for extension and closed for modification: when a new case arrives, add a class behind an interface the existing code already calls, instead of editing the class that already works. Meyer stated it for classes in 1988; in practice it is about where a new case lands.

In TheYard. The second database is the proof. Azure Cosmos DB arrived as new adapter classes behind the same three ports the relational store already implemented, and the rules and the use cases did not change (ADR: A second store on Cosmos DB). The composition root grew a second branch, which is where a new case is supposed to land. The relational backend, then the document backend, as the build wires them:

// The relational store, on SQL Server or SQLite. A factory rather than a
// scoped context: the two sources and the bid store are singletons that each
// want a context for one operation, and there is no request scope at startup
// when the catalogue is read. The interceptor puts every statement on the Admin
// tab; it is attached here so YardConnection stays a description of where the
// database is.
// How long the first of the five asks waits after a refusal (two seconds unless the
// configuration shortens it, which only a test that proves the fallback does).
var firstWait = StorePrepare.FirstWaitFrom(builder.Configuration);
var sqlStartup = new StartupTimings();
var sqlState = await sqlStartup.Time("prepare", stopping => StorePrepare.WithTriesAsync(() => YardDatabase.PrepareAsync(yard, seedVehicles, seedPhotos, stopping), firstWait), cancellation);
// The backend stands on the files until its store is attached: the same two
// ports answered out of the JSON, the null bid store, no accounts, with the
// synthetic scale-up still decorating the vehicle source (ADR: The relational
// store). Attached at once below when the store came up, or by the second
// chance when it comes up later (ADR: The relational store, the addendum on
// the second chance).
var sqlBackend = new Backend
{
    Key = StoreKeys.Relational,
    Name = yard.Describe(),
    Database = sqlState,
    Startup = sqlStartup,
    Inventory = new Stock(new SyntheticVehicleSource(seedVehicles, targetCount), seedPhotos),
    Bids = new BidBook(new MemoryBidStore()),
    Market = new Room(new Random(), builder.Configuration.GetValue("Market:GraceSeconds", Room.DefaultGraceSeconds)),
    Probe = _ => Task.FromResult(false),
};
// Identity's store over the accounts tables, keyed by the store, given a context from the
// request's scope. The type is the one AddEntityFrameworkStores would have registered for a
// user type with no roles; naming it here is what lets the other backend register a
// different one under the same interface. Registered whether or not the store came up: the
// Accounts slice asks the backend whether it is ready before it asks for the store
// (ADR: The onion cut into vertical slices, rule 4: the backend names no adapter).
builder.Services.AddKeyedScoped<IUserStore<YardUser>>(sqlBackend.Key, (services, _) =>
    new Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore<YardUser, YardDbContext, string>(
        services.GetRequiredService<YardDbContext>(),
        services.GetService<IdentityErrorDescriber>()));
// Everything that stands on the relational store, built from a state that
// says it came up. The loggers are attached the moment the host exists (the
// factory is read at call time, so an attach after startup gets them too).
StoreAttachment SqlAttachment(DatabaseState state)
{
    var sqlOptions = new DbContextOptionsBuilder<YardDbContext>();
    yard.Configure(sqlOptions);
    sqlOptions.AddInterceptors(new SqlLogInterceptor(sqlLog, currentRequest, TimeProvider.System));
    var contexts = new ContextFactory(sqlOptions.Options);
    // The same database without the interceptor, for the activity counters:
    // a batch every five seconds would fill the SQL log with the feature that
    // reads the SQL log, the observer effect the request ring designed out
    // (ADR: Site activity, and the line an address does not cross).
    var quietOptions = new DbContextOptionsBuilder<YardDbContext>();
    yard.Configure(quietOptions);
    var quietContexts = new ContextFactory(quietOptions.Options);
    if (loggers.Factory is not null)
    {
        contexts.Attach(loggers.Factory);
    }
    relationalContexts.Hold(contexts, quietContexts);
    return new StoreAttachment(
        state,
        new RelationalDiagnostics(contexts, yard.Describe(), () => loggers.Factory?.CreateLogger<RelationalDiagnostics>()),
        Catalogues.Sql(contexts, yard, targetCount, Catalogues.UpkeepFor(keepCatalogues, defaultStore, StoreKeys.Relational, servesBothSites)),
        new BidBook(new EfBidStore(contexts)),
        new EfActivityStore(quietContexts),
        token => YardDatabase.HasSeedAsync(contexts, token));
}
if (sqlState.Ready)
{
    sqlBackend.Attach(SqlAttachment(sqlState));
}
backendList.Add(sqlBackend);

Live from api/TheYard.Api/Shared/Wiring/StoreRegistration.cs, region sql-backend, read from this build at 99df7a8.

// The document store, when there is an account to talk to. Same question, same
// answer shape, other store: are the containers there with the keys this code
// was written for, and is the seed in them. A refusal falls through to the
// file-backed catalogue exactly as a missing schema does on SQL Server.
CosmosStore? cosmos = null;
StoreSecondChance.Plan? cosmosSecondChance = null;
if (cosmosConfigured)
{
    cosmos = CosmosConnection.Connect(
        configuredCosmos!,
        builder.Configuration["Cosmos:Database"] ?? "theyard",
        builder.Configuration["Cosmos:ContainerPrefix"] ?? "",
        // "managed-identity" on the deployed container; anything else, which
        // is what a developer's machine and the test runner have, means the
        // signed-in Azure CLI session.
        builder.Configuration["Cosmos:Credential"] ?? "azure-cli",
        AzureIds.ClientId(builder.Configuration),
        storeLog);
    // Every operation is filed under the request that caused it, the first one included.
    cosmos.Recorder.CurrentRequest = currentRequest;
    var cosmosStartup = new StartupTimings();
    var cosmosState = await cosmosStartup.Time("prepare", stopping => StorePrepare.WithTriesAsync(() => cosmos.Starting.PrepareAsync(seedVehicles, seedPhotos, stopping), firstWait), cancellation);
    var store = cosmos;
    // The relational backend's shape: the files until the store is attached (ADR: A
    // second store on Cosmos DB, and what it costs).
    var cosmosBackend = new Backend
    {
        Key = StoreKeys.Document,
        Name = "Azure Cosmos DB",
        Database = cosmosState,
        Startup = cosmosStartup,
        Diagnostics = new DocumentDiagnostics(cosmos),
        Inventory = new Stock(new SyntheticVehicleSource(seedVehicles, targetCount), seedPhotos),
        Bids = new BidBook(new MemoryBidStore()),
        Market = new Room(new Random(), builder.Configuration.GetValue("Market:GraceSeconds", Room.DefaultGraceSeconds)),
        Probe = _ => Task.FromResult(false),
    };
    // One document per account and one per address, and none of Identity's seven tables
    // (ADR: Accounts on a document store), keyed by the store the way the relational one is.
    builder.Services.AddKeyedScoped<IUserStore<YardUser>>(cosmosBackend.Key, (_, _) => new CosmosUserStore(store, TimeProvider.System));
    StoreAttachment CosmosAttachment(DatabaseState state) => new(
        state,
        new DocumentDiagnostics(store),
        // The same three ports, answered out of the document store.
        Catalogues.Cosmos(store, targetCount, Catalogues.UpkeepFor(keepCatalogues, defaultStore, StoreKeys.Document, servesBothSites)),
        new BidBook(new CosmosBidStore(store)),
        new CosmosActivityStore(store),
        store.Starting.ProbeAsync);
    if (cosmosState.Ready)
    {
        cosmosBackend.Attach(CosmosAttachment(cosmosState));
    }
    backendList.Add(cosmosBackend);
    cosmosSecondChance = new StoreSecondChance.Plan(
        cosmosBackend,
        () => store.Starting.PrepareAsync(seedVehicles, seedPhotos, CancellationToken.None),
        async state =>
        {
            var attachment = CosmosAttachment(state);
            await attachment.Inventory.WarmAsync(CancellationToken.None);
            await attachment.Bids.LoadAsync(CancellationToken.None);
            cosmosBackend.Attach(attachment);
        });
}

Live from api/TheYard.Api/Shared/Wiring/StoreRegistration.cs, region cosmos-backend, read from this build at 99df7a8.

The same shape holds the documents you are reading. A new page is one row in the server's catalogue and one entry in the front end's list of pages, and a test fails if the two ever disagree. This page arrived that way: two rows, no change to the code that serves documents.

Where it stops. The ports themselves changed once for the second store: every member became a Task, because the document store has no synchronous driver. That one change touched every caller once, and the record says so plainly rather than pretending the door was never opened (ADR: The ports learn to wait).

L, Liskov substitution

What it means. If code works with a type, it must keep working with anything that stands in for that type, without checking which one it got. Liskov's 1987 keynote put it as a property of types: a subtype must behave the way the supertype's users expect. For interfaces, that means any implementation can replace any other and the callers cannot tell.

In TheYard. The gate is the proof. The same xUnit suite runs on both stores: once with the relational store underneath, and again with Cosmos DB, by pointing the process at the account and running dotnet test again. Not a second suite written for the second store: the same facts, the other adapter, the same answers. The if in the block below is why the second pass is not run on every version: it runs when the version touched the API, the Cosmos infrastructure or the three specs that read both stores, and is carried forward from the version that last ran it otherwise. Between the two passes sit the twelve tests that do need the live account, which are the one set written for the second store. From the gate's own workflow, the job that reads the Cosmos DB account (the SQLite pass runs beside it in a job of its own since 1.0.5.4):

# The same xUnit suite again, booted on Cosmos DB: the process pointed at the emulator and the
# tests- containers, when the commit touched what it reads; between the store tests that drive
# the adapters directly and the three store specs in the browser.
- name: The Cosmos DB passes
  if: always()
  run: |
    d="$RAW/dotnet.result"; n="$RAW/node.result"; : > "$d"; : > "$n"
    t() { local s=$SECONDS code=0; "$@" || code=$?; echo "$code $((SECONDS - s))"; }
    export Cosmos__AccountEndpoint="$COSMOS_ENDPOINT" Cosmos__Credential=emulator
    read code s < <(t env Cosmos__CatalogueAccountEndpoint="$COSMOS_ACCOUNT" bash -c 'dotnet test api --no-build --filter "Store=cosmos" --logger "trx;LogFileName=xunit-live.trx" --results-directory "$RAW/trx" > "$RAW/xunit-live.txt" 2>&1')
    echo "live=$code" >> "$d"; echo "live_s=$s" >> "$d"
    export Cosmos__ContainerPrefix="tests-"
    if [ "$COSMOS_NEEDED" = 1 ]; then
      read code s < <(t bash -c 'dotnet test api --no-build --filter "Store!=cosmos" --logger "trx;LogFileName=xunit-cosmos.trx" --results-directory "$RAW/trx" > "$RAW/xunit-cosmos.txt" 2>&1')
      echo "oncosmos=$code" >> "$d"; echo "oncosmos_s=$s" >> "$d"
    else echo "oncosmos=skipped" >> "$d"; echo "oncosmos_s=0" >> "$d"; fi
    export YARD_API_PREBUILT=1 YARD_WEB_PREVIEW=1
    export PLAYWRIGHT_JSON_OUTPUT_FILE="$RAW/browser-cosmos.json" PLAYWRIGHT_JSON_OUTPUT_NAME="$RAW/browser-cosmos.json"
    if [ "$COSMOS_NEEDED" = 1 ]; then
      read code s < <(t bash -c 'npx playwright test tests/e2e/store-toggle.spec.ts tests/e2e/account.spec.ts tests/e2e/admin.spec.ts --workers=2 --retries=1 --reporter=list,json > "$RAW/browser-cosmos.txt" 2>&1')
      echo "browser_cosmos=$code" >> "$n"; echo "browser_cosmos_s=$s" >> "$n"
    else echo "browser_cosmos=skipped" >> "$n"; echo "browser_cosmos_s=0" >> "$n"; fi
    for port in 5173 5210; do fuser -k "$port/tcp" 2>/dev/null || true; done
    cat "$d" "$n"

Live from .github/workflows/gate.yml, region both-stores, read from this build at 99df7a8.

MemoryBidStore is the smaller case. It implements IBidStore in a dictionary, with the same compare-and-set rule the two real stores keep, and the tests of the use cases hand it in where a real store would go, so a use case can be tested with no database and no mocking framework. It stands in for a real store in production too: a backend whose store has not come up yet bids against it, and the bids are forgotten at restart. That is a deliberate limit, written down in ADR: The relational store.

Where it stops. Substitution is not complete everywhere, and the record says where: the Cosmos DB user store does not move the email claim when an address changes, and nothing in the site changes an address today (Known gaps in substitution). Sealing classes helps hold the principle from the other side: a class nothing can inherit from is a class no derived type can change the meaning of, which is why TheYard seals by default (Sealed by default).

I, interface segregation

What it means. No class should be forced to depend on methods it does not use. Shape an interface to the code that calls it, and prefer several small interfaces to one wide one.

In TheYard. The auction has three ports, not one repository, because the catalogue, the photos and the bids are read by different code at different times:

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

IStoreExperiment, the port behind the Admin tab's performance proof, has one method, because the Admin tab asks one question.

Where it stops. IActivityStore and ILogStore each carry one writer beside the handful of reads their callers ask for, and are not split, because splitting them would double the interfaces and allow no new swap. They stay whole until a caller needs only half (What is kept on purpose).

D, dependency inversion

What it means. The important code should not depend on the details underneath it; both should depend on an abstraction, and the abstraction should belong to the important code. In the rings, that is the move that makes the whole shape possible: the inner ring declares the interface it needs, the outer ring implements it, and at compile time every arrow points inward.

The inner ring owns the interface: Application declares IBidStore and uses it, EfBidStore and CosmosBidStore implement it from the outer ring, and the composition root decides which one each store gets

A preview. Open the port and its adapters in a new page to zoom in and follow it.

In TheYard. TheYard.Application declares IBidStore. EfBidStore in the relational adapter and CosmosBidStore in the document adapter implement it. Composition/StoreRegistration.cs decides which one a store gets, and every class receives what it needs through its constructor. Four tests read the compiled host and fail the build if a handler reaches a database, a Cosmos DB client or the service container, composes the bid services itself, queries a database, or registers a service anywhere but the composition root:

[Fact]
public void Endpoints_never_reach_a_store_or_the_service_container()
{
    // An endpoint reads the request, asks the Application ring, and writes the answer. A
    // database context, a Cosmos DB client or a service looked up by hand would make it a
    // second place where the rules and the wiring live.
    var result = Types.InAssembly(typeof(Program).Assembly)
        .That().MeetCustomRule(IsPartOfAnEndpointClass)
        .ShouldNot().HaveDependencyOnAny(
            "Microsoft.EntityFrameworkCore",
            "Microsoft.Azure.Cosmos",
            "Microsoft.Data.SqlClient",
            "Microsoft.Data.Sqlite",
            "System.Data.Common",
            "TheYard.Infrastructure.Cosmos",
            "TheYard.Infrastructure.YardDbContext",
            "TheYard.Infrastructure.Shared.Stores.ContextFactory",
            "System.IServiceProvider",
            "Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions")
        .GetResult();
    Assert.True(result.IsSuccessful, Explain(result));
}

[Fact]
public void Endpoints_reach_the_auction_only_through_the_Application_ring()
{
    // The order bids are composed in (the buyer's first, the room's second) and the price a
    // bid is measured against are Application's, in StandingReader and the bid handlers. An endpoint
    // that held the parts itself could compose them in another order.
    var result = Types.InAssembly(typeof(Program).Assembly)
        .That().MeetCustomRule(IsPartOfAnEndpointClass)
        .ShouldNot().HaveDependencyOnAny(
            "TheYard.Application.Shared.Auction.BidBook",
            "TheYard.Application.Shared.Auction.Room",
            "TheYard.Application.Shared.Auction.Stock")
        .GetResult();
    Assert.True(result.IsSuccessful, Explain(result));
}

[Fact]
public void Endpoints_see_the_auction_and_the_request_s_store_never_a_backend()
{
    // A backend is the shared wiring's: which adapter stands behind a store is said by its
    // diagnostics, and an endpoint reads the request's store through CurrentBackend's key,
    // name and auction (ADR: The onion cut into vertical slices, rule 4). The Admin tab's and
    // the health report's endpoints read every backend on purpose until their slices have
    // handlers of their own, which is rule 7's rung.
    var result = Types.InAssembly(typeof(Program).Assembly)
        .That().MeetCustomRule(type => IsPartOfAnEndpointClass(type)
            && !InNamespace(Outermost(type).Namespace, "TheYard.Api.Features.Admin")
            && !InNamespace(Outermost(type).Namespace, "TheYard.Api.Features.Health"))
        .ShouldNot().HaveDependencyOnAny("TheYard.Api.Shared.Stores.Backend", "TheYard.Api.Shared.Stores.Backends", "TheYard.Infrastructure.Cosmos.Shared.Stores.CosmosStore")
        .GetResult();
    Assert.True(result.IsSuccessful, Explain(result));
}

[Fact]
public void The_host_uses_the_sheds_assembly_only_from_the_shed_s_own_site()
{
    // The Shed is a whole application of its own, hosted in this process (ADR: The onion cut
    // into vertical slices, rule 5). ShedSite and ShedApplication may use its types; anything
    // else that did would fuse the two applications the merge kept apart by construction.
    var result = Types.InAssembly(typeof(Program).Assembly)
        .That().MeetCustomRule(type => Outermost(type).Name is not ("ShedSite" or "ShedApplication"))
        .ShouldNot().HaveDependencyOnAny(["TestProject"])
        .GetResult();
    Assert.True(result.IsSuccessful, Explain(result));
}

[Fact]
public void The_host_never_queries_a_database_itself()
{
    // A statement against a store belongs to the adapter for that store; the host asks the
    // adapter. Entity Framework's design-time factory and the composition root may name the
    // context type, and neither runs a query.
    var result = Types.InAssembly(typeof(Program).Assembly)
        .ShouldNot().HaveDependencyOnAny(
            "Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions",
            "Microsoft.EntityFrameworkCore.RelationalQueryableExtensions",
            "Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions",
            "Microsoft.EntityFrameworkCore.DbSet",
            "Microsoft.Data.SqlClient",
            "Microsoft.Data.Sqlite",
            "System.Data.Common.DbCommand",
            "System.Data.Common.DbConnection",
            "Microsoft.Azure.Cosmos.QueryDefinition",
            "Microsoft.Azure.Cosmos.Container")
        .GetResult();
    Assert.True(result.IsSuccessful, Explain(result));
}

[Fact]
public void Services_are_registered_only_in_the_composition_root()
{
    // Registration classes in Shared/, the slices' modules and Program.cs are where the container is filled.
    // Anywhere else, a registration would be wiring hidden inside behaviour.
    var result = Types.InAssembly(typeof(Program).Assembly)
        .That().MeetCustomRule(type => !IsCompositionRoot(type))
        .ShouldNot().HaveDependencyOnAny(
            "Microsoft.Extensions.DependencyInjection.IServiceCollection",
            "Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions",
            "Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions")
        .GetResult();
    Assert.True(result.IsSuccessful, Explain(result));
}

[Fact]
public void The_host_finds_nothing_at_runtime_outside_its_composition_root()
{
    // A dependency arrives by constructor (ADR: The onion cut into vertical slices, rule 6).
    // Reading the environment, a service container or the built app's configuration from
    // inside behaviour is wiring hidden where a test cannot hand it a value; the types in
    // CompositionRoot are where those are read, each for the reason beside it.
    Assert.Empty(RuntimeLookups(typeof(Program).Assembly.Location));
}

[Fact]
public void A_route_or_a_handler_is_handed_its_settings_never_the_configuration()
{
    // Rule 6 by its other door: IConfiguration injected into a route delegate is the built app's
    // configuration read per request. A setting is bound once, at composition, into a type the
    // route takes (SiteHosts carries Site:Url), so a test hands the route its value.
    using var module = ModuleDefinition.ReadModule(typeof(Program).Assembly.Location);
    var taking = module.GetTypes()
        .Where(type => !IsCompositionRoot(type) && (IsPartOfAnEndpointClass(type) || Outermost(type).Name.EndsWith("Handler", StringComparison.Ordinal)))
        .SelectMany(type => type.Methods)
        .Where(method => method.Parameters.Any(parameter => parameter.ParameterType.FullName == "Microsoft.Extensions.Configuration.IConfiguration"))
        .Select(method => $"{method.DeclaringType.FullName}.{method.Name} takes IConfiguration")
        .ToList();
    Assert.True(taking.Count == 0, string.Join(Environment.NewLine, taking));
}

[Fact]
public void The_application_ring_finds_nothing_at_runtime_at_all()
{
    // The handlers and services take their ports by constructor; a handler that took an
    // IServiceProvider and asked it for a port would pass the ring rule (System is allowed)
    // and hide its dependency from every fake-port test (the review of 1.0.4.0, finding 5).
    Assert.Empty(RuntimeLookups(typeof(TheYard.Application.Shared.Auction.StandingReader).Assembly.Location));
}

/// <summary>
/// Every call this site makes to Claude goes through IClaudeClient, whose one adapter writes a
/// usage document from every answer (ADR: Every Claude lane reports its usage). So the Anthropic
/// API's address and an Anthropic SDK namespace appear in that adapter's file and in no other
/// source file of the six projects or the page; a feature that called the API itself would be a
/// lane that reports no usage, which the record calls a defect.
/// </summary>
[Fact]
public void Claude_is_asked_only_through_the_one_client_that_reports_its_usage()
{
    string root = Repo.Root();
    string adapter = Path.Combine("api", "TheYard.Api", "Shared", "Usage", "AnthropicClaudeClient.cs");
    var sources = new[] { "TheYard.Data", "TheYard.Domain", "TheYard.Application", "TheYard.Infrastructure", "TheYard.Infrastructure.Cosmos", "TheYard.Api" }
        .SelectMany(project => Directory.EnumerateFiles(Path.Combine(root, "api", project), "*.cs", SearchOption.AllDirectories))
        .Concat(Directory.EnumerateFiles(Path.Combine(root, "src"), "*.ts*", SearchOption.AllDirectories))
        .Where(path => !path.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal)
                       && !path.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal))
        .ToList();
    Assert.Contains(sources, path => path.EndsWith(adapter, StringComparison.Ordinal));
    var calling = sources
        .Where(path => !path.EndsWith(adapter, StringComparison.Ordinal))
        .Where(path => File.ReadAllText(path) is var text
            && (text.Contains("api.anthropic.com", StringComparison.OrdinalIgnoreCase) || text.Contains("using Anthropic", StringComparison.Ordinal) || text.Contains("@anthropic-ai/", StringComparison.Ordinal)))
        .Select(path => Path.GetRelativePath(root, path))
        .ToList();
    Assert.True(calling.Count == 0, "these files reach the Anthropic API around IClaudeClient: " + string.Join(", ", calling));
    Assert.Contains(typeof(TheYard.Application.Shared.History.IUsageLog), typeof(TheYard.Api.Shared.Usage.AnthropicClaudeClient).GetConstructors().Single().GetParameters().Select(p => p.ParameterType));
    Assert.True(typeof(TheYard.Application.Shared.Claude.IClaudeClient).IsAssignableFrom(typeof(TheYard.Api.Shared.Usage.AnthropicClaudeClient)));
}
// #region host-opens-no-socket
[Fact]
public void The_host_opens_no_socket()
{
    // Only Infrastructure opens a socket (ADR: The onion cut into vertical slices, rule 8). The host builds a
    // request as data and hands it to an Outbound, which Infrastructure's OutboundHttp makes; a client, a
    // handler or a client factory in any host type but Program and a slice's Module is a second door to the
    // network that no adapter test sees. The allow list is empty.
    // The body is tests/rules/SocketRule.cs, the one the job hunt's suite runs over its inner rings too.
    var wrong = TheYard.Rules.SocketRule.Opens(typeof(Program).Assembly, name => name == "Program" || name.EndsWith("Module", StringComparison.Ordinal));
    Assert.True(wrong.Count == 0, string.Join(Environment.NewLine, wrong));
}
// #endregion host-opens-no-socket

Live from api/TheYard.Tests/OnionTests.cs, region host, read from this build at 99df7a8.

Where it stops. The server's clock is a static, read once at the edge and handed inward as a value, rather than a TimeProvider injected into every handler: the rules take the clock as an argument, which is what lets their tests fix time, and the extra parameter would buy the tests nothing (ADR: Onion and SOLID).

Five principles, one table

Letter The principle in one line Where it shows in TheYard What holds it
S One reason to change. A rule lives in Domain once; Program.cs is a list; one job per front-end file. FileHeaderTests, OnionTests
O Add a class, do not edit the core. Cosmos DB arrived as adapters behind the same ports; a page is a catalogue row. DocumentationCatalogTests
L A stand-in behaves the same. The same suite runs on both stores; MemoryBidStore. The gate's second xUnit pass
I Small interfaces, shaped to the caller. Three auction ports; a one-method experiment port. Review, and the record
D Depend on an abstraction the inner ring owns. IBidStore declared inside, implemented outside, wired in Composition/. OnionTests

How the build holds them

Architecture tests
19
File header tests
4
Sealed-by-default tests
5
Files with the header
164 of 164

Numbers read from the build when the page is opened. The architecture tests, by name:

Data_depends_on_nothing_outside_the_BCL
Data_has_no_behaviour
Domain_depends_on_nothing_outside_the_BCL_and_Data
Application_depends_only_on_Domain_Data_and_the_BCL
Domain_never_reaches_the_disk_the_network_or_the_clock
Application_never_reaches_the_disk_or_the_network
The_document_store_adapter_borrows_only_the_shared_user_from_the_relational_one
Infrastructure_adapts_and_decides_nothing
Endpoints_never_reach_a_store_or_the_service_container
Endpoints_reach_the_auction_only_through_the_Application_ring
Endpoints_see_the_auction_and_the_request_s_store_never_a_backend
The_host_uses_the_sheds_assembly_only_from_the_shed_s_own_site
The_host_never_queries_a_database_itself
Services_are_registered_only_in_the_composition_root
The_host_finds_nothing_at_runtime_outside_its_composition_root
A_route_or_a_handler_is_handed_its_settings_never_the_configuration
The_application_ring_finds_nothing_at_runtime_at_all
Claude_is_asked_only_through_the_one_client_that_reports_its_usage
The_host_opens_no_socket

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