Skip to content

ADR: Program.cs, explained

ADR: Program.cs, explained for a new developer

Status
accepted
Date
2026-09-02
Shipped as
1.0.0

24; rewritten on 2026-09-28 for 1.0.3.39, when the file became a composition root and its parts moved to files of their own (ADR: The composition root, split by job). Written at Steve's request for a developer new to ASP.NET Core, or new to this codebase, who opens the host file and wants to know what each part does and why it is the way it is.

In plain words

Program.cs is the file that starts the API. It reads like a table of contents, one line per part of the app, and this page walks each line and the file it leads to, with the code shown live from the running build.

What that is worth: a developer new to ASP.NET Core or to this code finds their way in one read, and the organization's newest hire can find where a change belongs without asking.

Context

Program.cs is the file that starts the API. It is now a table of contents: the builder, one line per concern that gets registered, the host built and started, the middleware, one line per feature that maps routes, and app.Run(). Each line leads to the file that shows how. This record walks those lines in order, and the samples are those files, read from this build.

The walk

The files are found by walking up

The dataset, the README, the docs and the photo manifest are located once, at startup, in Composition/HostPaths.cs. The API does not assume a fixed folder depth, because it is started from three places: dotnet run from the project folder, the test host from bin/Debug/..., and the published image from /app. FindUpward walks from the content root toward the disk root until it finds the named file, and throws a clear FileNotFoundException if it never does. HostPaths is registered, so an endpoint that serves a file asks for it as a parameter.

// Started from three different folders (dotnet run, the test host's bin
// directory, /app in the image), so nothing may assume a fixed depth. Walking
// up until the file appears works from all three, and the throw names what
// was missing instead of failing later as a null.
private static string FindUpward(string startDirectory, string relativePath)
{
    for (var dir = new DirectoryInfo(startDirectory); dir is not null; dir = dir.Parent)
    {
        string candidate = Path.Combine(dir.FullName, relativePath);
        if (File.Exists(candidate))
        {
            return candidate;
        }
    }
    throw new FileNotFoundException($"Could not locate {relativePath} in or above {startDirectory}");
}

Live from api/TheYard.Api/Shared/Wiring/HostPaths.cs, region find-upward, read from this build at 99df7a8.

The table of contents

What the file is today:

56 total
  12 comment
  7 blank
  37 code, across 0 endpoints

No route is mapped in Program.cs itself. Until 1.0.3.39 it was one file of 2,667 lines holding 48 endpoints; the record that replaced that decision says what changed and holds the new shape with a test.

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.

No class, no Main

The file uses top-level statements: C# lets the entry file read like a script, and the compiler writes the Program class and Main around it. The one visible trace is the last line, public sealed partial class Program;, which exists so the integration tests can name the class when they boot the host in memory with WebApplicationFactory<Program>.

/// <summary>
/// The app's entry point, exposed so the integration tests can boot the real host.
/// </summary>
public sealed partial class Program;

Live from api/TheYard.Api/Program.cs, region records-and-test-hook, read from this build at 99df7a8.

What the steps hand one another

Registration is a sequence, and a later step needs what an earlier one made: the accounts need the signing key, the kept log needs the stores, the page sweep needs the build's version. YardComposition carries those between the steps, filled once at startup and never read by a request except through what was registered. It is the one class in the composition with state, which is why it lives beside the other state types at the project's root and not in Composition/, where every class is static.

The stores come first

builder.AddTheYardStoresAsync (Composition/StoreRegistration.cs) is the only step that waits: it brings both stores up before anything is registered, because the answer decides what gets registered. The relational store is SQL Server when the deploy gave one and SQLite otherwise; the document store is there when an account is configured; each stands behind the same ports, on the JSON files until it comes up, and a store that refused at startup is asked again every thirty seconds for an hour (the second chance).

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

Nearly every registration in the steps is AddSingleton, one instance for the life of the process, because the dataset is loaded once and shared by every request and each store's standing bids live in memory beside it. InventoryService holds the expanded dataset in a Lazy, so a Scoped registration would expand 100,000 records per request. The two exceptions are decided per request and can only be: CurrentBackend, which store this request is on, and Identity's user store over it.

The rest of the registrations

Each is one file and one method, in the order the host needs them:

  • AddTheYardObservability (Composition/ObservabilityRegistration.cs): the rings behind the Admin tab, the kept log, and the request hook that files every request once.
  • AddTheYardSessions and AddTheYardAccounts (Composition/AuthRegistration.cs): the signing key and the session issuer first, because the activity feature keys visitor tokens with the same key; then Identity and the JWT read back from its cookie.
  • AddTheYardActivity (Composition/ActivityRegistration.cs) and AddTheYardEmail (Composition/EmailRegistration.cs): the collectors that write off the request path, and the one email.
  • AddTheYardApi (Composition/ApiRegistration.cs): snake_case bodies, one ProblemDetails for every failure, one log line per request, and the OpenAPI document.
  • AddTheYardTelemetry and AddTheYardAdmin: Application Insights where it is configured, and what the Admin tab reads that is not a ring.

Started before it serves

app.StartTheYardAsync (Composition/Startup.cs) runs after Build() and before anything is served: the loggers attached, a store that did not come up said out loud, and the default store's catalogue and bids loaded and timed. If the dataset is missing or malformed the process exits with the real error, the container's health check fails, and the deploy's verify step stops the roll, which is a better place to learn it than a 500 on the first visitor.

Middleware order, the part that bites

app.UseTheYardRequestPipeline (Composition/RequestPipeline.cs) holds every piece of middleware in one method, in the order it runs, with the reason beside each. Timing is outermost, so a failed request is recorded with the status that was actually sent; then the problem shape, the request log, the user, the session's renewal, the store's warmth, the error record, the cache rules, and the files last. Endpoints run at the end of the pipeline whichever line maps them, so the order that matters is the order in this one file.

// Timing, and it has to be the outermost thing here.
//
// Outermost, above UseExceptionHandler, because unwinding runs inner to outer.
// Placed below the handler, a request that threw would reach this finally
// before the handler had written anything, so every failed request would be
// recorded as a 200 with the handler's time left out. Here it records the
// status the caller actually received and the whole time they waited.
//
// Above the handler it sees the status that was actually sent. Above
// UseAuthentication too, so a request rejected with 401 is counted rather than
// short-circuited before it ever reaches the ring.
app.Use(async (context, next) =>
{
    long start = Stopwatch.GetTimestamp();
    recorder.MarkOperator(context); // the operator's key leaves with the operator's cookie (ADR-116)
    // The app's own time to its first byte, by name and milliseconds only, so a browser or a probe can tell it
    // from the wire's (ADR: A rendering service beside the API).
    context.Response.OnStarting(() =>
    {
        context.Response.Headers["Server-Timing"] = string.Create(
            System.Globalization.CultureInfo.InvariantCulture,
            $"app;dur={Stopwatch.GetElapsedTime(start).TotalMilliseconds:0.#}");
        return Task.CompletedTask;
    });
    try
    {
        await next();
    }
    finally
    {
        recorder.Record(context, Stopwatch.GetElapsedTime(start));
    }
});

Live from api/TheYard.Api/Shared/Wiring/RequestRecording.cs, region request-timing, read from this build at 99df7a8.

// What: every 500 and every exception goes into the error record the Admin tab
// reads. How: it records and rethrows rather than handling, so the exception
// handler above still owns the response. Why here: directly inside the
// exception handler, so it sees a failure in anything below it, signing in and
// renewing a session included. It sat below both until the pipeline lane, and
// an exception thrown while reading a token never reached the record.
app.Use(async (context, next) =>
{
    try
    {
        await next();
        if (context.Response.StatusCode >= 500)
        {
            errorLog.Record(context.Request.Path, context.Response.StatusCode, "server error response");
        }
    }
    catch (Exception ex)
    {
        // A caller who hung up is not a server error: the exception handler
        // answers it 499 and logs it at Information, so it is left out of
        // this record too, and the Admin tab's error count stays green.
        if (!ProblemHandler.CallerLeft(context, ex))
        {
            // The type and the frames, never the message. This record is
            // served at /api/errors with no sign-in, and an exception message
            // is where a framework writes a filesystem path, a connection
            // detail, or the value that broke a constraint; the exception
            // handler keeps it out of a response for the same reason. The
            // frames are source locations this repository already publishes.
            // The message is not lost: it goes to the console and to
            // Application Insights as a structured exception, behind a sign-in
            // (ADR: Error handling, the addendum on frames).
            errorLog.Record(context.Request.Path, 500, ex.GetType().Name, StackFrames.Of(ex));
        }
        throw;
    }
});

Live from api/TheYard.Api/Shared/Wiring/RequestRecording.cs, region error-log, read from this build at 99df7a8.

Endpoints: binding, then delegation

Each feature is a static class under Endpoints/ with one Map...Endpoints method and private, named handlers: VehicleEndpoints, BidEndpoints, DocumentationEndpoints, HealthEndpoints, ErrorEndpoints, AdminEndpoints, AccountEndpoints, and ReferenceEndpoints for the OpenAPI document and its page. A handler binds the request, calls the service that owns the rule, and shapes the reply; the rules live in Domain and Application. A handler's return type is a Results<...> union or a typed result, which is what the OpenAPI document reads, so naming the handlers changed nothing a client sees.

// All filters, sorting, and paging are optional GET parameters, applied
// server-side. The default page is the top 100 by auction time (live and
// ending soonest first). Responses are an envelope: { total, vehicles },
// with each vehicle carrying the server-derived auction facts.
// e.g. /api/vehicles?make=Ford&status=live&sort=price-asc&limit=100&offset=100
private static async Task<Results<Ok<VehiclePage>, ProblemHttpResult>> List(
    SearchVehiclesHandler handler,
    [AsParameters] VehicleQueryParams query,
    CancellationToken cancellation)
{
    if (!query.TryBuildFilter(out var filter, out var clock, out var sort, out var error))
    {
        // One failure shape for the whole API: the message a person can act on goes in
        // `detail`, never in a key only this endpoint uses.
        return TypedResults.Problem(detail: error, statusCode: 400, title: "The query could not be read");
    }
    // One handler answers the page (ADR: The onion cut into vertical slices, rule 7); this
    // file reads the query and writes the wire.
    var result = await handler.HandleAsync(new SearchVehiclesQuery(filter, clock, sort, query.EffectiveLimit, query.EffectiveOffset), cancellation);
    return TypedResults.Ok(new VehiclePage(result.Total, [.. result.Vehicles.Select(v => VehicleWire.ToWire(v, clock))]));
}

Live from api/TheYard.Api/Features/Vehicles/VehicleEndpoints.cs, region inventory-endpoint, read from this build at 99df7a8.

The two bid endpoints share one method, HandleBid, which answers three questions in order: is this session on this store, does the vehicle exist, does the domain accept the action, on the server's clock.

// Each route binds its wire and asks one handler (ADR: The onion cut into vertical slices,
// rule 7); the handler answers in the Application ring's words and this file turns them into
// the status codes the browser relies on: 401, 404, then 400.
private static async Task<Results<Ok<BidResult>, ProblemHttpResult>> PlaceBid(PlaceBidHandler handler, CurrentBackend current, HttpContext http, string id, BidRequest request, CancellationToken cancellation) =>
    Answer(await handler.HandleAsync(new PlaceBidCommand(id, http.UserId(), http.SessionIsOn(current), request.Amount), cancellation), current, id);

private static async Task<Results<Ok<BidResult>, ProblemHttpResult>> BuyNow(PlaceBidHandler handler, CurrentBackend current, HttpContext http, string id, CancellationToken cancellation) =>
    Answer(await handler.HandleAsync(new PlaceBidCommand(id, http.UserId(), http.SessionIsOn(current), null), cancellation), current, id);

private static async Task<Ok<IReadOnlyDictionary<string, BidView>>> MyBids(ReadMyBidsHandler handler, HttpContext http, CancellationToken cancellation) =>
    TypedResults.Ok(await handler.HandleAsync(new ReadMyBidsQuery(http.UserIdOrNull()), cancellation));

private static async Task<Ok<BidHistory>> History(ReadBidHistoryHandler handler, HttpContext http, CancellationToken cancellation) =>
    TypedResults.Ok(await handler.HandleAsync(new ReadBidHistoryQuery(http.UserId()), cancellation));

// The room's round, and the caller's own badges riding back with it, so a page does not need
// a second request to find out it has been outbid.
private static async Task<Ok<TickResult>> Tick(RoomRoundHandler handler, HttpContext http, CancellationToken cancellation)
{
    var round = await handler.HandleAsync(new RoomRoundCommand(http.UserIdOrNull()), cancellation);
    return TypedResults.Ok(new TickResult(round.Raised, round.Bids));
}

private static async Task<Results<NoContent, ProblemHttpResult>> ResetMine(ResetBidsHandler handler, HttpContext http, CancellationToken cancellation) =>
    await handler.HandleAsync(new ResetBidsCommand(http.UserIdOrNull()), cancellation)
        ? TypedResults.NoContent()
        : TypedResults.Problem(detail: "Sign in to reset your bids.", statusCode: 401, title: "Not signed in");

private static Results<Ok<BidResult>, ProblemHttpResult> Answer(BidAnswer answer, CurrentBackend current, string id) => answer.Kind switch
{
    BidAnswerKind.SessionElsewhere => TypedResults.Problem(
        detail: $"This session was opened on another store. Sign in on {current.Name} to bid here.",
        statusCode: 401, title: "The bid was rejected"),
    BidAnswerKind.NoSuchVehicle => TypedResults.Problem(detail: "No vehicle has that id.", statusCode: 404, title: "No such vehicle"),
    BidAnswerKind.Rejected => TypedResults.Problem(detail: answer.Reason, statusCode: 400, title: "The bid was rejected"),
    _ => TypedResults.Ok(new BidResult(
        answer.Outcome!.Value.Kind.ToString().ToLowerInvariant(),
        answer.Outcome.Value.Amount,
        answer.Standing,
        VehicleWire.ToWire(answer.Vehicle!, answer.Clock!.Value))),
};

Live from api/TheYard.Api/Features/Bids/BidEndpoints.cs, region bid-handling, read from this build at 99df7a8.

Liveness, readiness, and the Admin tab

/healthz answers "ok" if the process is up; the container's HEALTHCHECK asks it. /readyz runs the checks that gate traffic and answers 503 until the files the app needs are in place; the deploy's verify step asks it. /api/health returns every check with its timing for the Admin tab.

// Three endpoints, three audiences. /healthz is the container's HEALTHCHECK
// and answers only "the process is up". /readyz is the deploy's Verify step
// and answers 503 until the files are in place. /api/health is the Admin tab
// and carries the timings. A process can be alive and not yet ready, and the
// orchestrator treats those differently (ADR-010).
app.MapGet("/healthz", Liveness)
    .WithName("Liveness")
    .WithTags("Health")
    .WithSummary("Is the process up")
    .WithDescription("The container's own health check. Answers ok the moment the process is listening and says nothing else.")
    .Produces<string>(StatusCodes.Status200OK, "text/plain")
    // Answered by routing itself, so a poll never reads the session cookie
    // (RequestPipeline.cs, the routing region).
    .ShortCircuit();

// Only the checks that gate it, and only those get run: the database probe is
// two SQL statements whose answer readiness discards, and this endpoint is
// polled by the orchestrator and by every deploy.
app.MapGet("/readyz", Readiness)
    .WithName("Readiness")
    .WithTags("Health")
    .WithSummary("Should traffic be sent here")
    .WithDescription("The deploy's verify step. Only the checks that gate readiness run, and the database is not one "
        + "of them: a container whose store is gone still serves the catalogue from files.")
    .Produces<string>(StatusCodes.Status200OK, "text/plain")
    .ProducesProblem(StatusCodes.Status503ServiceUnavailable)
    .ShortCircuit();

app.MapGet("/api/health", Health)
    .WithName("GetHealth")
    .WithTags("Health")
    .WithSummary("Every check, timed, and the build that answered")
    .WithDescription("The Admin tab's health card. One check per store, named by the store, so a container running "
        + "both says which one is unavailable.");

Live from api/TheYard.Api/Features/Health/HealthEndpoints.cs, region probes, read from this build at 99df7a8.

The single-page app, last

app.MapTheYardSpa (Composition/SpaRegistration.cs) answers any address that is not an API route or a real file with index.html, so a missing bundle file is a 404 and never a page dressed as a script.

// The SPA fallback serves index.html for app routes only; an address that
// looks like a file (a hashed bundle name that no longer exists, say) is a
// 404, never a page dressed as a script.
app.MapFallbackToFile("{*path:nonfile}", "index.html");

Live from api/TheYard.Api/Shared/Wiring/SpaRegistration.cs, region spa-fallback, read from this build at 99df7a8.

What to change when

  • A new endpoint: a Map... line and a private handler in the feature's file under Endpoints/, or a new static class there with its own Map...Endpoints line in Program.cs; binding and delegation only, and a test in api/TheYard.Tests that boots the host and calls it.
  • A new service: one line in the registration step it belongs to, AddSingleton unless it holds per-request state.
  • A new piece of middleware: in RequestPipeline.cs, at the place its order demands, with the reason beside it.
  • A new document: one line in DocumentationCatalog.cs and one in src/library/records.ts or pages.ts; a test fails if the two disagree.

Addendum, 2026-09-08: two stores in one file

The walk above still reads top to bottom, and two of its stops changed shape when the document store moved in beside the relational one (ADR: One container, both stores).

The persistence region no longer chooses a store. It reads both settings, the SQL connection string and the Cosmos DB endpoint, and creates the two rings and the request describer early, because the interceptor that feeds the SQL ring is attached to a context factory built by hand before the container exists. The migrate-and-seed region then builds one Backend per store: the relational one always, the document one when there is an endpoint, each brought up and timed on its own, each holding its own InventoryService, BidService and MarketService, and each saying how to build Identity's store over its accounts. The three services left the container entirely; an endpoint takes CurrentBackend, which is scoped to the request and resolved once from the request's header, cookie or the container's default.

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

Identity is registered once and unconditionally; its store is the one thing about it chosen per request. The health check runs one database probe per store. The metrics endpoint answers the store the request is on at the top level, as it always did, and lists every store below it. And two endpoints were added for the toggle at the top of the page.

// The Store bar at the top of the page (ADR: One container, both stores, and
// its addendum on the toggle moving to the sites). What stores this container
// runs, which one is this site's default, which one this request is on, and
// the other site's address. There is no switch endpoint: the bar's other
// segment is a link to the other site, so the address bar changes and each
// site stays one store's site. A stale yard-store cookie is expired here, on
// the first page load that carries it.
app.MapGet("/api/stores", AdminObservabilityRoutes.Stores)
    .WithName("GetStores")
    .WithTags("Stores")
    .WithSummary("Which stores this container runs, and which one this request is on")
    .WithDescription("A request names a store with the X-Yard-Store header (sql or cosmos) or gets the site's default. "
        + "The other site, if there is one, is the same code with the other default.");

Live from api/TheYard.Api/Features/Admin/Operations/AdminEndpoints.cs, region stores-endpoints, read from this build at 99df7a8.

The numbers in the section above are the file's numbers on the day this addendum was written; the test that holds them to the file does not care which day that was.

Addendum, 2026-09-09: one endpoint for the bar, not two

The toggle moved to the sites the next morning (ADR: One container, both stores, the addendum of that name), and the second of the two endpoints above went with it. CurrentBackend is resolved from the request's header or the container's default now, not from a cookie; POST /api/stores/select is gone, and GET /api/stores expires the cookie the old toggle set when a request still carries one. The live block above shows what is left.

Addendum, 2026-09-15: the wire shape is a record now

The paragraph on wireFormat above says VehicleWire.ToWire serialises each vehicle to a JSON node and appends the auction facts, which is why the host's options could not reach it. That stopped being how it works when the API started describing itself (ADR: The API describes itself): ToWire builds a VehicleView, a record with the dataset's twenty-nine fields and the five derived ones, and the public endpoints answer through TypedResults.Ok, which serialises with the host's own options, the same snake_case policy that ConfigureHttpJsonOptions sets for request bodies, and which carries the response type into the document where TypedResults.Json carries nothing. wireFormat stays for the Results.Json calls the operator endpoints still make, and both paths apply the one policy. Neither the names nor the order of the values on the wire changed.

Addendum, 2026-09-30: the request pipeline, by name

Naming the same file in The Shed, Steve pointed out that the word pipeline can mean too many things to be clear. This site alone serves ADR: The deploy pipeline beside this record. The middleware file is now Composition/RequestPipeline.cs and the call app.UseTheYardRequestPipeline(host), ASP.NET Core's own name for it ("The ASP.NET Core request pipeline consists of a sequence of request delegates", Microsoft Learn, ASP.NET Core Middleware). Nothing in the order changed; the file moved and its type was renamed.

Addendum, 2026-09-30: documentation, spelled out

Naming the same kind of file in The Shed, Steve pointed out that "Docs" was an abbreviation and hid what the file does. The endpoints that serve the records, their pictures and diagrams, the Bicep, the resume and /about are now Endpoints/DocumentationEndpoints.cs, mapped by app.MapDocumentationEndpoints(). The version is not among them here (/api/version is in HealthEndpoints), so the name says documentation and nothing more. Routes and behaviour are unchanged. The catalog those endpoints read (slug to file, plus the diagrams) is DocumentationCatalog.cs for the same reason, held by DocumentationCatalogTests.

Where it sits

This record is about the host Api alone: Program.cs is a table of contents, and Composition/ is the composition root, the one place where the outer rings' classes are bound to the ports the inner rings define. That binding is dependency inversion, with Application owning the interfaces while Infrastructure and Infrastructure.Cosmos supply them through constructors, and each registration file under Composition/ has one job, which is single responsibility. The cost is more files to open than a single Program.cs, so a newcomer follows a line to its file before reading any code. A service with a handful of endpoints and one store would read better as one short Program.cs.

Addendum, 2026-10-20 (1.0.3.188): no bag, and no startup method

The paragraphs above on YardComposition and on app.StartTheYardAsync (Composition/Startup.cs) describe the file until 1.0.3.187. From 1.0.3.188 Program.cs reads the build's version and commit and the platform's three settings (the web app's name and the managed identity's door) once, into BuildInfo and HostIdentity, and hands each registration only the values it needs. The work Startup.cs did when the host was built runs as hosted services when the host starts, one per concern, registered by AddTheYardStartup, with The Shed's stopper registered last (ADR: The onion cut into vertical slices, rules 2 and 6).

Addendum, 2026-10-20 (1.0.3.189): a loop over the slices

From 1.0.3.189 the second half of Program.cs is no longer a list of app.Map... lines. Each feature is a slice under Features/ with a Module.cs that registers and maps it, and Program.cs finds every module, registers them after the shared steps, and maps them after the shared pipeline, with the single-page fallback last. The shared registrations moved from Composition/ to Shared/ and keep their calls here, one per line (ADR: The onion cut into vertical slices, rule 1).

Files

Addendum, 2026-10-03: endpoints ask the Application ring

The section on endpoints says a handler calls the service that owns the rule. A bidding or catalogue handler now asks one Application type, Auction (api/TheYard.Application/Shared/Auction/StandingReader.cs), which composes the catalogue, the bids and the room in the order the rules need; the three services stay on each Backend and no endpoint holds them. HandleBid takes a function of the auction, the vehicle and the clock. The relational context factory the 2026-09-08 addendum mentions moved from the host into the relational adapter (api/TheYard.Infrastructure/Shared/Stores/ContextFactory.cs), because it builds YardDbContext; the host still creates it before the container exists and only asks it for contexts. OnionTests holds both changes.

Addendum, 2026-10-07 (1.0.3.89): the catalogue loads beside the server

"Started before it serves" above stopped being true of the catalogue. StartTheYardAsync still attaches the loggers and says a missing store out loud before anything is served, but the default store's bids and catalogue now load beside the server rather than before it, so a roll answers in seconds instead of minutes (ADR: The ports learn to wait, the addendum on listening first). A dataset that cannot be loaded still ends the process: the failure is logged and the host is stopped, and readiness, which now waits on the catalogue, keeps the deploy's Verify step from passing.

Addendum, 2026-10-07 (1.0.3.92): the pipeline line, reordered

Program.cs did not change: app.UseTheYardRequestPipeline(host) is still one line, and the order still lives in Composition/RequestPipeline.cs. What that file holds did. The files now come straight after the problem shape and the error record, before routing, the user, the session and the store, where Microsoft's middleware order puts them; routing is called out loud instead of left to run at the top; the forwarded headers run before anything that reads the visitor's address or scheme; the health probes end at routing; and the HTTP logger, which never wrote a line, is gone. Every placement carries its reason beside its line (ADR: The order of the request pipeline).

// What: matches the request to an endpoint. How: an explicit UseRouting; left
// out, ASP.NET Core adds one at the very top. Why here: after the files, which
// never need a route, and before the user and the endpoint. The health probes
// are marked ShortCircuit (HealthEndpoints.cs), so routing answers them right
// here and they skip reading the session cookie. That is all it saves them: they
// are not under /api, so the session's renewal and the store's warmth never
// applied to them, and the timing ring already left them out by path. Anything
// that needs the matched endpoint later (a CORS policy, a rate limit, an output
// cache policy) goes below this line.
app.UseRouting();

Live from api/TheYard.Api/Shared/Wiring/RequestPipeline.cs, region routing, read from this build at 99df7a8.

Addendum, 2026-10-29: three lines of comment, and the same thirty-seven of code

The shape above went from 53 lines to 56, all three of them comment. The stores are prepared before anything is registered, and that call now takes the cancellation that stops it; the only honest value for it here is none, because the lifetime that owns ApplicationStopping is made by Build() eleven lines further down. So this file says so, in three lines, rather than a registration deep in Shared/Wiring hard-coding CancellationToken.None twice where no reader would look for the decision (ADR: The numbers that may only fall, the addendum on reading a whole signature). Naming a token this file does not have is a composition root's job; the code count is unchanged, and no route is mapped here still.

Enforced by

Not machine-checked. Held by review.

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