Skip to content

ADR: The composition root, split by job

ADR: The composition root, split by job

Status
accepted
Date
2026-09-28
Shipped as
1.0.3.39

Steve approved the target shape on 28 September: Program.cs a table of contents, one file per concern, one static class per feature.

In plain words

Program.cs used to be 2,667 lines. Now it is a short list, and each part of the app is set up in a file of its own: one file for each kind of setup, and one file for each feature's routes.

What that is worth: a developer goes straight to the one file that matters, and two people can change two features without editing the same file.

Context

ADR: Program.cs, explained kept the host in one file on purpose, and named what would change its mind: the composition and the routes no longer fitting in a reader's head together. Measured at 1.0.3.36, before anything moved:

Before
Program.cs 2,667 lines: 934 comment, 151 blank, 1,582 code
Endpoints mapped in it 48
Regions in it 66
Live samples in the documents that point at it 38, across 16 documents

A reader looking for how a bid is handled scrolled past the stores, the rings, the accounts and the pipeline to find it, and a reader looking for the middleware order found it spread across four places, because an app.Use line runs in registration order wherever it sits among the routes.

Decision

Program.cs lists what the app is made of and in what order, and each line leads to the file that shows how:

  • Composition/: one static class per registration step (the stores, the observability rings, sessions and accounts, activity, email, the wire's shape, telemetry, the Admin tab's readers), the startup work after Build(), the whole pipeline in one method with the reason beside each piece, and the single-page fallback.
  • Endpoints/: one static class per feature (vehicles, bids, documents, health, errors, the Admin tab, accounts, the OpenAPI reference), each with one Map...Endpoints method and private handlers named for what they answer.
  • The records a feature binds or answers with sit beside it (BidRequest in the bids file, ClientErrorReport in the errors file).

What the approved sketch guessed and the real code answered differently, where the real code won:

  • The stores are brought up before anything is registered, and that is awaited, so the step is AddTheYardStoresAsync and Program.cs awaits it.
  • The steps hand one another what they made (the signing key, the stores, the kept log). YardComposition carries it, filled once at startup. It holds state, so it sits at the project's root beside HostStart, ErrorRings and KeepWarmState; every class in Composition/ and Endpoints/ is static.
  • Moved code kept its namespace, TheYard.Api, because thirty-two test files import it and no existing test was to change.
  • No Options/ or Background/ folder yet: no setting was bound through the options pattern to move, and the background services already live one per file at the project's root. Only code that left Program.cs went into the new folders; the root files are named in the review as a later pass.

The numbers

Before (1.0.3.36) After (1.0.3.39)
Program.cs 2,667 lines 54 lines
Endpoints mapped in Program.cs 48 0
Files that map routes 1 9, under Endpoints/ and Composition/
The OpenAPI document the same operations and schemas; the paths and the tag list in a new order, because they follow the order routes are mapped in (Admin now first appears before Accounts)

Every region moved with its code under its own name, and every live sample that pointed at Program.cs points at the file the code is in now.

What holds it

  • CompositionRootTests: Program.cs under eighty lines, no route mapped from Program.cs itself, every route mapped from a file under Endpoints/ or Composition/, and every class in those folders static.
  • XmlSummaryTests: every public class and record in the solution carries a summary saying what it is for, and every positional record names each parameter; the generated migrations are excused by file name, and the test fails if an excused file disappears.
  • ApiDocumentTests, unchanged: the document the API publishes about itself. The ship's check also read the document from the running API before the move and after each of the nine commits and compared them, with the paths and the tag list taken as sets.
  • Every test that existed before this change passes without an edit.
/// <summary>The line ceiling Program.cs is held under.</summary>
private const int Ceiling = 80;

/// <summary>A call that maps a route, on anything: MapGet, MapPost, MapFallbackToFile and the rest.</summary>
private static readonly Regex MapsARoute = new(
    @"\.Map(Get|Post|Put|Delete|Patch|Methods|Fallback\w*|Group|OpenApi|ScalarApiReference|HealthChecks)\(",
    RegexOptions.Compiled);

private static string Api() => Path.Combine(Repo.Root(), "api", "TheYard.Api");

private static IEnumerable<string> Sources() =>
    Directory.EnumerateFiles(Api(), "*.cs", SearchOption.AllDirectories)
        .Where(path => !path.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal)
            && !path.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal));

private static string Relative(string path) => Path.GetRelativePath(Api(), path).Replace('\\', '/');

[Fact]
public void Program_cs_is_a_loop_under_the_ceiling()
{
    string[] lines = File.ReadAllLines(Path.Combine(Api(), "Program.cs"));
    Assert.True(lines.Length < Ceiling, $"Program.cs is {lines.Length} lines; the ceiling is {Ceiling}");
    string program = string.Join('\n', lines);
    Assert.Contains("Modules.InThisHost()", program, StringComparison.Ordinal);
    Assert.Contains("module.Register(", program, StringComparison.Ordinal);
    Assert.Contains("module.Map(", program, StringComparison.Ordinal);
}

[Fact]
public void Program_cs_maps_no_route_itself()
{
    string program = File.ReadAllText(Path.Combine(Api(), "Program.cs"));
    var direct = MapsARoute.Matches(program).Select(match => match.Value).ToList();
    Assert.True(direct.Count == 0, "Program.cs maps routes itself: " + string.Join(", ", direct));
}

[Fact]
public void Every_route_is_mapped_from_a_slice_or_the_one_shared_fallback()
{
    var outside = Sources()
        .Select(Relative)
        .Where(path => !path.StartsWith("Features/", StringComparison.Ordinal) && path != "Shared/Wiring/SpaRegistration.cs")
        .Where(path => MapsARoute.IsMatch(File.ReadAllText(Path.Combine(Api(), path))))
        .ToList();
    Assert.True(outside.Count == 0, "these map routes outside Features/ and the fallback: " + string.Join(", ", outside));
}

[Fact]
public void Every_slice_folder_has_a_module_and_every_module_is_sealed()
{
    string features = Path.Combine(Api(), "Features");
    var slices = Directory.EnumerateDirectories(features, "*", SearchOption.AllDirectories)
        .Where(folder => Directory.EnumerateFiles(folder, "*.cs").Any())
        .Select(folder => Path.GetRelativePath(features, folder).Replace('\\', '/'))
        .ToList();
    Assert.NotEmpty(slices);
    var withoutAModule = slices.Where(slice => !File.Exists(Path.Combine(features, slice, "Module.cs"))).ToList();
    Assert.True(withoutAModule.Count == 0, "these slices have no Module.cs: " + string.Join(", ", withoutAModule));
    var modules = typeof(Program).Assembly.GetTypes().Where(type => type.IsClass && typeof(TheYard.Api.Shared.Wiring.IModule).IsAssignableFrom(type)).ToList();
    Assert.Equal(slices.Count, modules.Count);
    Assert.All(modules, module => Assert.True(module.IsSealed && module.Name == "Module", $"{module.FullName} should be a sealed class named Module"));
}

[Fact]
public void Every_class_that_registers_or_maps_is_static()
{
    // A registration step and an endpoint class hold no state; a slice's Module is the one instance
    // class beside them. Every file under Shared/Wiring/ is a registration step or the settings one
    // reads (ADR-114), so the rule holds there whole. Anywhere else under Shared/ or Features/ it is
    // held for a file that maps or registers (it names the route builder or the service collection):
    // the shared concerns' services, the hosted services under Shared/Hosted/ and the guest sites under
    // Shared/Sites/ are running things with their dependencies in their constructors. Records are
    // the wire shapes and the settings a registration reads.
    var declaration = new Regex(@"^\s*public\s+((?:\w+\s+)*)class\s+(\w+)", RegexOptions.Multiline);
    var open = Sources()
        .Select(Relative)
        .Where(path => path.StartsWith("Shared/Wiring/", StringComparison.Ordinal)
            || ((path.StartsWith("Features/", StringComparison.Ordinal) || path.StartsWith("Shared/", StringComparison.Ordinal)) && !path.EndsWith("/Module.cs", StringComparison.Ordinal)
                && Regex.IsMatch(File.ReadAllText(Path.Combine(Api(), path)), @"\bIEndpointRouteBuilder\b|\bIServiceCollection\b|\.Map(Get|Post|Put|Delete|Patch|Group)\(")))
        .SelectMany(path => declaration.Matches(File.ReadAllText(Path.Combine(Api(), path)))
            .Where(match => !match.Groups[1].Value.Split(' ', StringSplitOptions.RemoveEmptyEntries).Contains("static"))
            .Select(match => $"{path}: {match.Groups[2].Value}"))
        .ToList();
    Assert.True(open.Count == 0, "these classes are not static: " + string.Join(", ", open));
    Assert.Contains(Sources(), path => Relative(path).StartsWith("Features/", StringComparison.Ordinal));
}

Live from api/TheYard.Tests/CompositionRootTests.cs, region composition-root-rules, read from this build at 99df7a8.

Addendum, 2 October: the front end's entry, the same way

Steve asked for the site's front-end entry, src/main.tsx, to read like Program.cs, and set the rule behind it for every file: no large, tangled files; anyone should be able to open a file and see its intention.

main.tsx held the stylesheet list, the order those sheets load in and why, the two window-level error handlers, and the React mount with its boundary, all in one file of comments and markup. It is now the front end's table of contents: one line per part, in order, with the file that holds the details beside it.

// styles/globalStyles.ts: the site-wide stylesheets, loaded by the import above, in order
captureAdminKey(); // lib/adminKey.ts: keep the operator's key before the address bar is tidied
captureLinkedInReturn(); // lib/linkedin.ts: keep LinkedIn's callback result for its card, the same way
reportUncaughtErrors(); // app/reportUncaughtErrors.ts: report crashes an error boundary never sees
mountTheYard('root'); // app/mount.tsx: draw the site into <div id="root"> in index.html

Live from src/main.tsx, region bootstrap, read from this build at 99df7a8.

The parts moved, unchanged in what they do, to files named for their one job: src/styles/globalStyles.ts loads the stylesheets in their order, src/app/reportUncaughtErrors.ts reports the crashes an error boundary never sees, and src/app/mount.tsx draws the site inside the boundary. Each opens with the Does, Does not and Used by lines that FileHeaderTests reads, and that test already holds every file under src/app to 300 lines.

What that is worth: a reader opens the entry file and sees the whole start-up on one screen, and each part has one file to change.

Where it sits

This is a host Api decision: Program.cs became a table of contents, with one static class per registration step in Composition/ and one per feature in Endpoints/, and no inner ring moved. Each file has one job, so changing how bids are mapped means opening BidEndpoints.cs and nothing that wires the stores (single responsibility). It cost YardComposition, a small stateful object that hands the signing key and the stores from one step to the next, and twenty-nine files across Composition/ and Endpoints/ where there was one. A host small enough to read on one screen would be clearer as one file again.

Addendum, 2026-10-20 (1.0.3.188): the steps take what they need by name

From 1.0.3.188 YardComposition is gone. It was a record every registration took whole and wrote into, and Composition/Startup.cs read eleven fields off it: a service locator in a record's clothes, and the first thing the review of 20 October named (ADR: The onion cut into vertical slices, rule 2). Each registration now takes what it needs as parameters, and Program.cs passes them by name. Bringing the stores up answers a PreparedStores that nobody writes into after it is made. What Startup.cs did is now one hosted service per concern in Hosted/, each handed its dependencies by constructor: the stores said out loud, the scratch database cleaned up, the error rings kept, the catalogue warmed beside the server, the page sweep at the roll, the keep-warm loop, and The Shed stopped after the drain. SliceTests fails if the record comes back.

Addendum, 2026-10-20 (1.0.3.189): the folders by kind became folders by feature

The split by job above put every endpoint in Endpoints/ and every registration in Composition/, folders named for the kind of code they held, and CompositionRootTests held that shape. From 1.0.3.189 the host is cut the other way: one folder per feature under Features/ (Bids, Vehicles, Accounts, Docs, Health, and the Admin tab's Operations, Plan and Cloud), each with its endpoints and a Module.cs that registers and maps it, and what every feature shares under Shared/. The plan's, the cloud cards' and the accounts' registrations moved into their modules. CompositionRootTests is rewritten to the new shape rather than deleted: Program.cs a loop under eighty lines that maps nothing, every route mapped from a slice or the one fallback, every slice folder with a sealed Module, and every registering or mapping class static. SliceTests adds the rule that a slice uses no other slice (ADR: The onion cut into vertical slices, rule 1).

Files

Enforced by

2 rules in the rulebook cite this record, each held by a test on every release.

The rule What holds it In the last gate
Program.cs is a table of contents under eighty lines that maps no route itself, every route is mapped from a file under Endpoints/ or Composition/, and every class in those two folders is static CompositionRootTests 10 of 10 passed
Every public class and record in the solution says what it is for in an XML summary, and every positional record names each parameter; only the generated migrations are excused, by name XmlSummaryTests 4 of 4 passed
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