Onion architecture, the practices
TheYard is a used-vehicle auction platform built in the open: a .NET 11 API, a React front end, and
two databases underneath it. Its server is built as an onion, and the record of that decision, with
every ring, every rule the build runs and what each one stops, is
ADR: Onion and SOLID, how this codebase holds them.
This page is the practical half. Each section is one practice you can copy, shown with a drawing or a
whole file read from the running build, and each section has an address of its own so a link can
land on it.
In plain words
The server is built in rings. The auction's rules sit in the middle, the code that carries out what a
visitor asks for wraps them, and the database code and the web endpoints sit on the outside. Code may
use the rings inside it and never the ones outside it. This page follows one bid through those rings,
shows how the inner ring can save a bid without knowing which database it is talking to, why the
rules never read the clock, how 19 tests keep the shape from slipping, and how a small codebase gets
the same shape from folders instead of projects.
What that is worth: a developer can copy each practice into their own codebase this week, and the
organization gets business rules that are tested in milliseconds with no database, plus a structure
the build defends on every push instead of one that depends on a reviewer noticing.
The words this page uses
- Ring: one layer of the code. Here each inner ring is its own .NET project; in a smaller
codebase a ring can be a folder.
- Dependency: code in one place using a type from another, through a project reference, a
using line, or a call inside a method body.
- Domain: the rules of the business, here the auction's: who may bid, how much, and when.
- Use case: one thing a visitor does, such as placing a bid, written as a method that runs the
rules and the stores in the right order.
- Port: an interface the inner code declares for something it needs from outside, such as a
place to keep bids.
- Adapter: a class in an outer ring that implements a port against one real thing, such as SQL
Server or Cosmos DB.
- Host: the web application itself, the endpoints that read a request and write the answer.
- Composition root: the one place, at startup, where the real classes are created and handed to
the code that needs them.
- BCL: the .NET base class library, the
System namespaces every .NET program has.
The rule in one sentence
Dependencies point inward: code may use the rings inside it and never the ones outside it.

A preview. Open the rings diagram in a new page to zoom in and follow it.
Innermost first: Data (the dataset's shapes, with no behaviour), Domain (the rules), Application
(the use cases and the ports), and outside them the adapters and the host. What lives in each ring
is listed in the record, under
The rings, and is not
repeated here.
Jeffrey Palermo, who named the pattern in 2008, put the same rule this way: "All code can depend on
layers more central, but code cannot depend on layers further out from the core." Everything else on
this page is a way of keeping that sentence true once the code is large and the week is busy.
A request walks the rings
The rule is easiest to see by following one request. A signed-in buyer bids on a vehicle with
POST /api/vehicles/{id}/bids, and the code meets the rings in this order:

A preview. Open the bid's walk in a new page to zoom in and follow it.
- The host reads. The endpoint checks that the session belongs to this store (401 if not) and
that the vehicle exists (404 if not), reads the server's clock once, and asks
PlaceBidHandler, the
one handler that request has (ADR-115).
- Application composes.
PlaceBidHandler reads the vehicle as it stands through StandingReader
and hands the bid to BidBook, which keeps everybody's bids. It lets one bid through at a time and
folds everybody's bids into the vehicle, so the rules see the price as it stands.
- Application asks Domain.
BidBook calls BidRules.ResolveBid with the vehicle, the amount,
the clock and whether anybody has already bought it.
- Domain decides. The answer is a
BidOutcome: refused because the vehicle is sold, the auction
is not live or the bid is under the minimum; won at the buy-now price; or accepted. It is a pure
function, so the same inputs give the same answer every time.
- Application saves through the port. On yes,
BidBook calls IBidStore.TrySaveAsync, which
writes only if the standing still has the version it read (a compare-and-set), and only then records
the bid in memory, so a failed or overtaken write means the bid did not happen anywhere.
- An adapter writes. Whichever adapter the composition root wired in at startup, for SQL or for
Cosmos DB, writes the row or the document.
- The host answers. A refusal becomes a 400 with the reason; a bid that stands becomes a 200 with
the bid and the vehicle as it now stands.
The practice: an endpoint reads the request, asks one use case, and writes the answer. It does not
decide anything and does not put services together itself. Two of the onion's architecture tests hold that
(Endpoints_never_reach_a_store_or_the_service_container and
Endpoints_reach_the_auction_only_through_the_Application_ring).
The code in the order the bid meets it: three files whole, and the one method between them. The
endpoint,
api/TheYard.Api/Features/Bids/BidEndpoints.cs:
using System.ComponentModel;
using Microsoft.AspNetCore.Http.HttpResults;
using TheYard.Application.Features.Bids;
namespace TheYard.Api.Features.Bids;
public static class BidEndpoints
{
public static IEndpointRouteBuilder MapBidEndpoints(this IEndpointRouteBuilder app)
{
#region bid-endpoints
app.MapPost("/api/vehicles/{id}/bids", PlaceBid)
.RequireAuthorization()
.WithName("PlaceBid")
.WithTags("Bids")
.WithSummary("Bid on a vehicle")
.WithDescription("Whole dollars. The rules run on the server: a sold vehicle takes no bid, an amount at or above "
+ "the buy-now price wins outright at that price, and anything else has to clear the minimum next bid "
+ "measured against the room's standing price. A session bids on the store it was opened on.")
.ProducesProblem(StatusCodes.Status400BadRequest)
.ProducesProblem(StatusCodes.Status401Unauthorized)
.ProducesProblem(StatusCodes.Status404NotFound);
app.MapPost("/api/vehicles/{id}/buy-now", BuyNow)
.RequireAuthorization()
.WithName("BuyNow")
.WithTags("Bids")
.WithSummary("Buy a vehicle outright")
.WithDescription("No body: the vehicle is named in the address. Refused when the vehicle has no buy-now price, "
+ "is already sold, or its auction is not live.")
.ProducesProblem(StatusCodes.Status400BadRequest)
.ProducesProblem(StatusCodes.Status401Unauthorized)
.ProducesProblem(StatusCodes.Status404NotFound);
#region market-endpoints
app.MapGet("/api/bids", MyBids)
.WithName("GetMyBids")
.WithTags("Bids")
.WithSummary("The caller's standing on every vehicle they have bid on")
.WithDescription("Keyed by vehicle id. Signed out, this is an empty map rather than a 401: the page asks for it "
+ "on every load, and no bids is the true answer for a visitor with no session.");
#region history
app.MapGet("/api/bids/history", History)
.RequireAuthorization()
.WithName("GetBidHistory")
.WithTags("Bids")
.WithSummary("The caller's bids, newest first, with the vehicle each is on")
.ProducesProblem(StatusCodes.Status401Unauthorized);
#endregion history
app.MapPost("/api/market/tick", Tick)
.RequireAuthorization()
.WithName("TickRoom")
.WithTags("Bids")
.WithSummary("One round of bidding by the room")
.WithDescription("The simulated room bids against the caller's auctions and a page of live ones, on the server's "
+ "clock. Driven by the page rather than a timer, and only by a signed-in visitor, because moving the "
+ "room moves everybody's prices.")
.ProducesProblem(StatusCodes.Status401Unauthorized);
#endregion market-endpoints
app.MapDelete("/api/bids", ResetMine)
.RequireAuthorization()
.WithName("ResetMyBids")
.WithTags("Bids")
.WithSummary("Forget the caller's bids, and the room's answers to them")
.WithDescription("One person's start-over. Nobody else's bids move.")
.ProducesProblem(StatusCodes.Status401Unauthorized);
#endregion bid-endpoints
return app;
}
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));
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))),
};
}
public sealed record BidRequest([property: Description("Whole dollars, at or above the vehicle's min_next_bid.")] int Amount);
Live from api/TheYard.Api/Features/Bids/BidEndpoints.cs, region *, read from this build at 99df7a8.
The use case the bid route asks, one command and its handler,
api/TheYard.Application/Features/Bids/PlaceBidHandler.cs:
public sealed class PlaceBidHandler(StandingReader standings, IBidWriter bids, Func<AuctionClock> clock) : ICommandHandler<PlaceBidCommand, BidAnswer>
{
public async Task<BidAnswer> HandleAsync(PlaceBidCommand request, CancellationToken cancellation)
{
if (!request.SessionOnThisStore)
{
return BidAnswer.Refused(BidAnswerKind.SessionElsewhere, null);
}
var now = clock();
cancellation.ThrowIfCancellationRequested();
if (await standings.FindAsync(request.VehicleId, cancellation) is not { } vehicle)
{
return BidAnswer.Refused(BidAnswerKind.NoSuchVehicle, null);
}
var outcome = request.Amount is { } amount
? await bids.PlaceBidAsync(vehicle.Vehicle, amount, now, request.UserId, cancellation)
: await bids.BuyNowAsync(vehicle.Vehicle, now, request.UserId, cancellation);
if (outcome.Kind == BidOutcomeKind.Rejected)
{
return BidAnswer.Refused(BidAnswerKind.Rejected, outcome.Reason);
}
return new BidAnswer(
BidAnswerKind.Placed,
outcome,
null,
standings.BidsOf(request.UserId).TryGetValue(request.VehicleId, out var standing) ? standing : null,
await standings.FindAsync(request.VehicleId, CancellationToken.None) ?? vehicle,
now);
}
}
Live from api/TheYard.Application/Features/Bids/PlaceBidHandler.cs, region place-bid, read from this build at 99df7a8.
The method that asks the rules and then calls the port, from the part of BidBook that moves a
price,
api/TheYard.Application/Shared/Auction/BidBook.Bidding.cs:
public async Task<BidOutcome> PlaceBidAsync(Vehicle vehicle, int amount, AuctionClock clock, string userId, CancellationToken cancellation)
{
await LoadAsync(cancellation);
await _gate.WaitAsync(cancellation);
try
{
for (int attempt = 1; attempt <= Attempts; attempt++)
{
var (held, version) = await CurrentAsync(vehicle.Id, CancellationToken.None);
var merged = held is null ? vehicle : vehicle.RaisedTo(held.Amount, held.BidCount);
var outcome = BidRules.ResolveBid(merged, amount, clock, held?.SoldBuyNow ?? false);
if (outcome.Kind == BidOutcomeKind.Rejected)
{
return outcome;
}
var state = new BidState(
outcome.Amount,
merged.BidCount + 1,
WonBuyNow: outcome.Kind == BidOutcomeKind.Won,
AtMs: clock.NowMs);
var next = StandingFold.Next(held, userId, state);
if (await _store.TrySaveAsync(userId, vehicle.Id, state, next, version, CancellationToken.None))
{
_ledger.Record(userId, vehicle.Id, state, next);
return outcome;
}
}
return BidOutcome.Rejected(MovedReason);
}
finally
{
_gate.Release();
}
}
Live from api/TheYard.Application/Shared/Auction/BidBook.Bidding.cs, region place, read from this build at 99df7a8.
The rules,
api/TheYard.Domain/Shared/Auction/BidRules.cs.
Nothing in it is async, nothing in it reads a file, and the clock arrives as an argument:
using System.Globalization;
using TheYard.Data;
namespace TheYard.Domain.Shared.Auction;
public enum BidOutcomeKind
{
Rejected,
Accepted,
Won,
}
public readonly record struct BidOutcome(BidOutcomeKind Kind, int Amount, string? Reason)
{
public static BidOutcome Rejected(string reason) => new(BidOutcomeKind.Rejected, 0, reason);
public static BidOutcome Accepted(int amount) => new(BidOutcomeKind.Accepted, amount, null);
public static BidOutcome Won(int amount) => new(BidOutcomeKind.Won, amount, null);
}
public static class BidRules
{
public const int MaxBid = 10_000_000;
public static int Increment(int currentBid) =>
currentBid < 5_000 ? 100 : currentBid < 20_000 ? 250 : 500;
public static int MinNextBid(Vehicle vehicle) =>
vehicle.CurrentBid is { } bid ? bid + Increment(bid) : vehicle.StartingBid;
public const string SoldReason = "This vehicle has been sold.";
public static BidOutcome ResolveBid(Vehicle vehicle, int amount, AuctionClock clock, bool sold)
{
if (sold)
{
return BidOutcome.Rejected(SoldReason);
}
if (amount > MaxBid)
{
return BidOutcome.Rejected($"A bid can be at most ${MaxBid.ToString("N0", CultureInfo.InvariantCulture)}.");
}
var status = AuctionSchedule.StatusFor(vehicle.Id, clock);
if (status == AuctionStatus.Live && vehicle.BuyNowPrice is { } buyNow && amount >= buyNow)
{
return BidOutcome.Won(buyNow);
}
if (status == AuctionStatus.Upcoming)
{
return BidOutcome.Rejected("This auction has not started yet.");
}
if (status == AuctionStatus.Ended)
{
return BidOutcome.Rejected("This auction has ended.");
}
int min = MinNextBid(vehicle);
return amount < min
? BidOutcome.Rejected($"Bid must be at least ${min.ToString("N0", CultureInfo.InvariantCulture)}.")
: BidOutcome.Accepted(amount);
}
public static BidOutcome ResolveBuyNow(Vehicle vehicle, AuctionClock clock, bool sold)
{
if (sold)
{
return BidOutcome.Rejected(SoldReason);
}
if (vehicle.BuyNowPrice is not { } buyNow)
{
return BidOutcome.Rejected("This vehicle has no Buy Now price.");
}
return AuctionSchedule.StatusFor(vehicle.Id, clock) == AuctionStatus.Live
? BidOutcome.Won(buyNow)
: BidOutcome.Rejected("Buy Now is only available while the auction is live.");
}
}
Live from api/TheYard.Domain/Shared/Auction/BidRules.cs, region *, read from this build at 99df7a8.
The inner ring owns the interface
The rule in one sentence has an obvious problem. Application has to save a bid, and the database is
outside it. The answer is dependency inversion, the D in SOLID: the inner ring declares the interface
it needs, in its own words, and the outer ring implements it. At compile time every arrow points
inward, at the interface. Only the call at runtime travels outward, and it travels through a type the
inner ring owns.

A preview. Open the port and its adapters in a new page to zoom in and follow it.
Microsoft's architecture guide for .NET describes the same move: "defining abstractions, or
interfaces, in the Application Core, which are then implemented by types defined in the
Infrastructure layer." TheYard runs it twice over, because two stores, SQL and Cosmos DB, each
adapt the same auction ports in Ports.cs (IVehicleSource, IPhotoManifestSource, IBidStore
and IVehicleCatalogue). Since the auction's reads and writes were split, the use cases reach them
through a reading and a writing interface each (IStockReader; IBidReader and IBidWriter;
IRoomReader and IRoomWriter), and the rules have no idea which store is answering.
The practice: name the port for what the inner ring needs (IBidStore) and keep the technology
out of the name (ISqlBidRepository would leak it), and keep every type the port mentions inside the
inner ring. Give
it an in-memory implementation beside it that keeps the same rules, as MemoryBidStore is here, and
the use cases can be tested with no database and no mocking framework.
The ports, whole,
api/TheYard.Application/Shared/Auction/Ports.cs:
using TheYard.Data;
namespace TheYard.Application.Shared.Auction;
public interface IVehicleSource
{
Task<IReadOnlyList<Vehicle>> LoadAsync(CancellationToken cancellation);
}
public interface IPhotoManifestSource
{
Task<IReadOnlyList<PhotoEntry>> LoadAsync(CancellationToken cancellation);
}
public interface IBidStore
{
Task<IReadOnlyList<StoredBid>> LoadAsync(CancellationToken cancellation);
Task<IReadOnlyList<StoredStanding>> LoadStandingsAsync(CancellationToken cancellation);
Task<StoredStanding?> ReadStandingAsync(string vehicleId, CancellationToken cancellation);
Task<IReadOnlyList<StoredBid>> BidsOnAsync(string vehicleId, CancellationToken cancellation);
Task<bool> TrySaveAsync(string userId, string vehicleId, BidState state, VehicleStanding standing, string? expectedVersion, CancellationToken cancellation);
Task ClearAsync(string userId, CancellationToken cancellation);
}
public interface IVehicleCatalogue
{
int Target { get; }
CatalogueFillPace Pace { get; }
Task<int> FilledAsync(CancellationToken cancellation);
Task FillAsync(IReadOnlyList<CatalogueEntry> batch, CancellationToken cancellation);
Task<SegmentCounts> CountAsync(CatalogueFilter filter, CancellationToken cancellation);
Task<IReadOnlyList<CatalogueEntry>> PageAsync(CatalogueFilter filter, CatalogueOrder order, int skip, int take, CancellationToken cancellation);
Task<IReadOnlyList<CatalogueEntry>> FindAsync(IReadOnlyCollection<string> ids, CancellationToken cancellation);
Task<InventoryFacets> FacetsAsync(CancellationToken cancellation);
}
Live from api/TheYard.Application/Shared/Auction/Ports.cs, region *, read from this build at 99df7a8.
The relational adapters, whole: EF Core over Azure SQL Database or SQLite,
api/TheYard.Infrastructure/Shared/Auction/EfSources.cs.
EfBidStore is the last class in the file:
using System.Globalization;
using Microsoft.EntityFrameworkCore;
using TheYard.Application.Shared.Auction;
using TheYard.Data;
namespace TheYard.Infrastructure.Shared.Auction;
public sealed class EfVehicleSource(IDbContextFactory<YardDbContext> factory) : IVehicleSource
{
public async Task<IReadOnlyList<Vehicle>> LoadAsync(CancellationToken cancellation)
{
using var db = await factory.CreateDbContextAsync(cancellation);
return await db.Vehicles.AsNoTracking().OrderBy(row => row.Seq).Select(row => row.ToVehicle()).ToListAsync(cancellation);
}
}
public sealed class EfPhotoManifestSource(IDbContextFactory<YardDbContext> factory) : IPhotoManifestSource
{
public async Task<IReadOnlyList<PhotoEntry>> LoadAsync(CancellationToken cancellation)
{
using var db = await factory.CreateDbContextAsync(cancellation);
return await db.Photos.AsNoTracking().OrderBy(row => row.Seq)
.Select(row => new PhotoEntry(row.File, row.Style, row.Title))
.ToListAsync(cancellation);
}
}
public sealed partial class EfBidStore(IDbContextFactory<YardDbContext> factory) : IBidStore
{
public async Task<IReadOnlyList<StoredBid>> LoadAsync(CancellationToken cancellation)
{
using var db = await factory.CreateDbContextAsync(cancellation);
return await db.Bids.AsNoTracking().Select(row => new StoredBid(
row.UserId,
row.VehicleId,
new BidState(row.Amount, row.BidCount, row.WonBuyNow, row.AtMs)))
.ToListAsync(cancellation);
}
public async Task<IReadOnlyList<StoredBid>> BidsOnAsync(string vehicleId, CancellationToken cancellation)
{
using var db = await factory.CreateDbContextAsync(cancellation);
return await db.Bids.AsNoTracking().Where(row => row.VehicleId == vehicleId).Select(row => new StoredBid(
row.UserId,
row.VehicleId,
new BidState(row.Amount, row.BidCount, row.WonBuyNow, row.AtMs)))
.ToListAsync(cancellation);
}
public async Task<bool> TrySaveAsync(string userId, string vehicleId, BidState state, VehicleStanding standing, string? expectedVersion, CancellationToken cancellation)
{
using var db = await factory.CreateDbContextAsync();
await using var transaction = await db.Database.BeginTransactionAsync();
if (expectedVersion is not null && !await TryMoveStandingAsync(db, vehicleId, standing, long.Parse(expectedVersion, CultureInfo.InvariantCulture), CancellationToken.None))
{
return false;
}
if (expectedVersion is null)
{
db.Standings.Add(RowOf(vehicleId, standing, version: 1));
}
await StageBuyerRowAsync(db, userId, vehicleId, state, cancellation);
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
return false;
}
catch (DbUpdateException) when (expectedVersion is null)
{
await transaction.RollbackAsync();
if (await StandingExistsAsync(vehicleId, CancellationToken.None))
{
return false;
}
throw;
}
await transaction.CommitAsync();
return true;
}
private static async Task StageBuyerRowAsync(YardDbContext db, string userId, string vehicleId, BidState state, CancellationToken cancellation)
{
var existing = await db.Bids.FindAsync(userId, vehicleId);
if (existing is null)
{
existing = new BidRow
{
UserId = userId,
VehicleId = vehicleId,
Amount = state.Amount,
BidCount = state.BidCount,
WonBuyNow = state.WonBuyNow,
AtMs = state.AtMs,
};
db.Bids.Add(existing);
}
else
{
existing.Amount = state.Amount;
existing.BidCount = state.BidCount;
existing.WonBuyNow = state.WonBuyNow;
existing.AtMs = state.AtMs;
}
if (db.Database.IsSqlite())
{
existing.RowVersion = Guid.NewGuid().ToByteArray();
}
}
public async Task ClearAsync(string userId, CancellationToken cancellation)
{
using var db = await factory.CreateDbContextAsync();
await using var transaction = await db.Database.BeginTransactionAsync();
var touched = await db.Bids.Where(bid => bid.UserId == userId).Select(bid => bid.VehicleId).ToListAsync();
await db.Standings.Where(row => touched.Contains(row.VehicleId)).ExecuteDeleteAsync();
await db.Bids.Where(bid => bid.UserId == userId).ExecuteDeleteAsync();
await transaction.CommitAsync();
}
}
Live from api/TheYard.Infrastructure/Shared/Auction/EfSources.cs, region *, read from this build at 99df7a8.
The document store adapters, whole: the Cosmos DB SDK,
api/TheYard.Infrastructure.Cosmos/Shared/Auction/CosmosSources.cs.
CosmosBidStore is the last class in this one too:
using System.Net;
using Microsoft.Azure.Cosmos;
using TheYard.Application.Shared.Auction;
using TheYard.Data;
using TheYard.Infrastructure.Cosmos.Shared.Stores;
namespace TheYard.Infrastructure.Cosmos.Shared.Auction;
public sealed class CosmosVehicleSource(CosmosStore store) : IVehicleSource
{
public async Task<IReadOnlyList<Vehicle>> LoadAsync(CancellationToken cancellation)
{
var documents = await store.QueryAsync<VehicleDocument>(
store.Vehicles, new QueryDefinition("SELECT * FROM c"), partitionKey: null, "cross-partition", cancellation: cancellation);
return documents.OrderBy(d => d.Seq).Select(d => d.ToVehicle()).ToList();
}
}
public sealed class CosmosPhotoManifestSource(CosmosStore store) : IPhotoManifestSource
{
public async Task<IReadOnlyList<PhotoEntry>> LoadAsync(CancellationToken cancellation)
{
var documents = await store.QueryAsync<PhotoDocument>(
store.Photos, new QueryDefinition("SELECT * FROM c"), partitionKey: null, "cross-partition", cancellation: cancellation);
return documents.OrderBy(d => d.Seq).Select(d => d.ToEntry()).ToList();
}
}
public sealed partial class CosmosBidStore(CosmosStore store) : IBidStore
{
private const string Partition = "pinned to the buyer";
public async Task<IReadOnlyList<StoredBid>> LoadAsync(CancellationToken cancellation)
{
var documents = await store.QueryAsync<BidDocument>(
store.Bids,
new QueryDefinition("SELECT * FROM c WHERE c.user_id != @standing").WithParameter("@standing", StandingDocument.Partition),
partitionKey: null,
"cross-partition", cancellation: cancellation);
return documents.Select(d => d.ToStoredBid()).ToList();
}
public async Task<IReadOnlyList<StoredBid>> BidsOnAsync(string vehicleId, CancellationToken cancellation)
{
var documents = await store.QueryAsync<BidDocument>(
store.Bids,
new QueryDefinition("SELECT * FROM c WHERE c.id = @vehicle AND c.user_id != @standing")
.WithParameter("@vehicle", vehicleId)
.WithParameter("@standing", StandingDocument.Partition),
partitionKey: null,
"cross-partition", cancellation: cancellation);
return documents.Select(d => d.ToStoredBid()).ToList();
}
public async Task<bool> TrySaveAsync(string userId, string vehicleId, BidState state, VehicleStanding standing, string? expectedVersion, CancellationToken cancellation)
{
if (!await TryWriteStandingAsync(vehicleId, standing, expectedVersion, CancellationToken.None))
{
return false;
}
await SaveBuyerAsync(userId, vehicleId, state, CancellationToken.None);
return true;
}
private async Task SaveBuyerAsync(string userId, string vehicleId, BidState state, CancellationToken cancellation)
{
for (int attempt = 1; ; attempt++)
{
try
{
await WriteAsync(userId, vehicleId, state, cancellation);
return;
}
catch (CosmosException ex) when (attempt < 3
&& ex.StatusCode is HttpStatusCode.PreconditionFailed or HttpStatusCode.Conflict)
{
}
}
}
private async Task WriteAsync(string userId, string vehicleId, BidState state, CancellationToken cancellation)
{
var existing = await store.ReadAsync<BidDocument>(store.Bids, vehicleId, userId, Partition, cancellation: cancellation);
var document = new BidDocument
{
Id = vehicleId,
UserId = userId,
Amount = state.Amount,
BidCount = state.BidCount,
WonBuyNow = state.WonBuyNow,
AtMs = state.AtMs,
};
if (existing is null)
{
await store.CreateAsync(store.Bids, document, userId, Partition, cancellation: cancellation);
}
else
{
await store.ReplaceAsync(store.Bids, document, vehicleId, userId, existing.ETag, Partition, cancellation: cancellation);
}
}
public async Task ClearAsync(string userId, CancellationToken cancellation)
{
var ids = await store.QueryAsync<string>(
store.Bids,
new QueryDefinition("SELECT VALUE c.id FROM c WHERE c.user_id = @user").WithParameter("@user", userId),
partitionKey: userId,
Partition, cancellation: cancellation);
if (ids.Count > 0)
{
await store.DeleteBatchAsync(store.Bids, userId, ids, Partition, cancellation: CancellationToken.None);
await ForgetStandingsAsync(ids, CancellationToken.None);
}
}
}
Live from api/TheYard.Infrastructure.Cosmos/Shared/Auction/CosmosSources.cs, region *, read from this build at 99df7a8.
And the one place that names an adapter: the composition root,
api/TheYard.Api/Shared/Wiring/StoreRegistration.cs,
building the relational store's backend and then the document store's. Look for
new BidBook(new EfBidStore(contexts)) in the first and new BidBook(new CosmosBidStore(store))
in the second:
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);
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),
};
builder.Services.AddKeyedScoped<IUserStore<YardUser>>(sqlBackend.Key, (services, _) =>
new Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore<YardUser, YardDbContext, string>(
services.GetRequiredService<YardDbContext>(),
services.GetService<IdentityErrorDescriber>()));
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);
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.
CosmosStore? cosmos = null;
StoreSecondChance.Plan? cosmosSecondChance = null;
if (cosmosConfigured)
{
cosmos = CosmosConnection.Connect(
configuredCosmos!,
builder.Configuration["Cosmos:Database"] ?? "theyard",
builder.Configuration["Cosmos:ContainerPrefix"] ?? "",
builder.Configuration["Cosmos:Credential"] ?? "azure-cli",
AzureIds.ClientId(builder.Configuration),
storeLog);
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;
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),
};
builder.Services.AddKeyedScoped<IUserStore<YardUser>>(cosmosBackend.Key, (_, _) => new CosmosUserStore(store, TimeProvider.System));
StoreAttachment CosmosAttachment(DatabaseState state) => new(
state,
new DocumentDiagnostics(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 rules take the clock as a value
A rule that reads DateTime.UtcNow for itself gives a different answer every time it runs, and a
test of it can only check what happens "now". A rule that is handed the time gives the same answer for
the same inputs, so a test can pin any moment it likes: one millisecond before an auction opens, the
millisecond it opens, the last millisecond before it ends.
TheYard reads the clock at the edge, in the host. Its
api/TheYard.Api/Shared/Instance/Clocks.cs
turns the current moment into an AuctionClock (now, and the UTC midnight the day's auctions are
scheduled from), and every endpoint that needs the time passes that value inward:
namespace TheYard.Api.Shared.Instance;
public static class Clocks
{
public static AuctionClock Now() => AuctionClock.Utc(UtcNow());
public static DateTimeOffset UtcNow() => DateTimeOffset.UtcNow;
}
Live from api/TheYard.Api/Shared/Instance/Clocks.cs, region *, read from this build at 99df7a8.
The clock itself is a value in Domain,
api/TheYard.Domain/Shared/Auction/AuctionClock.cs:
namespace TheYard.Domain.Shared.Auction;
public readonly record struct AuctionClock(long NowMs, long AnchorMs)
{
public static AuctionClock Utc(DateTimeOffset utcNow)
{
var midnight = new DateTimeOffset(utcNow.UtcDateTime.Date, TimeSpan.Zero);
return new AuctionClock(utcNow.ToUnixTimeMilliseconds(), midnight.ToUnixTimeMilliseconds());
}
}
Live from api/TheYard.Domain/Shared/Auction/AuctionClock.cs, region *, read from this build at 99df7a8.
And the rule that uses it, whole,
api/TheYard.Domain/Shared/Auction/AuctionSchedule.cs.
Every auction's opening and closing times are worked out from the vehicle's id and the anchor, so
nothing about the schedule is stored, and the status is a comparison of two numbers:
namespace TheYard.Domain.Shared.Auction;
public enum AuctionStatus
{
Upcoming,
Live,
Ended,
}
public readonly record struct AuctionWindow(long StartsAtMs, long EndsAtMs);
public static class AuctionSchedule
{
private const long HourMs = 60L * 60 * 1000;
private const long DayMs = 24 * HourMs;
private const long ScheduleLookbackMs = 2 * DayMs;
private const long ScheduleSpanMs = 7 * DayMs;
private const long MinDurationMs = 2 * DayMs;
private const long ExtraDurationMs = 2 * DayMs;
public static AuctionWindow Window(string vehicleId, long anchorMs)
{
uint hash = Fnv1a.Hash(vehicleId);
double endFraction = hash % 100_000 / 100_000.0;
double durationFraction = hash / 100_000 % 1_000 / 1_000.0;
long endsAt = (long)Math.Round(anchorMs - ScheduleLookbackMs + endFraction * ScheduleSpanMs);
long durationMs = (long)Math.Round(MinDurationMs + durationFraction * ExtraDurationMs);
return new AuctionWindow(endsAt - durationMs, endsAt);
}
public static AuctionStatus Status(AuctionWindow window, long nowMs)
{
if (nowMs < window.StartsAtMs)
{
return AuctionStatus.Upcoming;
}
return nowMs < window.EndsAtMs ? AuctionStatus.Live : AuctionStatus.Ended;
}
public static AuctionStatus StatusFor(string vehicleId, AuctionClock clock) =>
Status(Window(vehicleId, clock.AnchorMs), clock.NowMs);
}
Live from api/TheYard.Domain/Shared/Auction/AuctionSchedule.cs, region *, read from this build at 99df7a8.
One test, from
api/TheYard.Tests/AuctionScheduleTests.cs,
pins the moment one millisecond either side of each edge of a window. Clock is built once at the top
of the class from a fixed date, so the anchor never depends on the day the test runs. With a clock the
rule read for itself, this test could not be written:
[Fact]
public void Status_boundaries_are_start_inclusive_and_end_exclusive()
{
var window = AuctionSchedule.Window("some-id", Clock.AnchorMs);
Assert.Equal(AuctionStatus.Upcoming, AuctionSchedule.Status(window, window.StartsAtMs - 1));
Assert.Equal(AuctionStatus.Live, AuctionSchedule.Status(window, window.StartsAtMs));
Assert.Equal(AuctionStatus.Live, AuctionSchedule.Status(window, window.EndsAtMs - 1));
Assert.Equal(AuctionStatus.Ended, AuctionSchedule.Status(window, window.EndsAtMs));
}
Live from api/TheYard.Tests/AuctionScheduleTests.cs, region boundaries, read from this build at 99df7a8.
The practice: read the clock once, at the edge, and pass it inward as a value. The build holds
this one too: Domain_never_reaches_the_disk_the_network_or_the_clock reads every method body in
Domain for a call to DateTime.Now, DateTime.UtcNow, DateTime.Today or their DateTimeOffset
twins, and fails on the first it finds. .NET 8 added TimeProvider for code that needs a clock it can
swap, and the record says why a plain value is enough here
(What is kept on purpose).
How many things a class may be handed
The S in SOLID is the half of this page's record that is not about rings, and it is held by a
number rather than by a yes-or-no test, because one more constructor parameter is never the
moment to object. The number is wide_service_classes in .github/quality-ratchet.json: how many
classes are handed six or more things (ADR: The numbers that may only fall). Six collaborators is
more than one job, and a class with more than one job is changed for more than one reason.
Count parameters, not commas. The rule used to read five commas on the line a class was
declared on, which is a different question and gets a different answer. A generic type argument
carries a comma of its own, so Func<CancellationToken, Task<string?>> read as two parameters and
three classes taking four and five were counted as wide; and a parameter list long enough to wrap
puts its last parameters on the lines below, so seven classes taking six to eight were not counted
at all. It now reads the whole signature and splits it on a comma at the list's own bracket depth,
outside any angle brackets:
def handed(taken):
"""The parameters in a parameter list, split where a reader would split them."""
if taken is None:
return []
depth = angle = 0
out, cur = [], ""
for ch in taken:
if ch == "(":
depth += 1
elif ch == ")":
depth -= 1
elif ch == "<":
angle += 1
elif ch == ">":
angle = max(0, angle - 1)
if ch == "," and depth == 0 and angle == 0:
out.append(cur)
cur = ""
else:
cur += ch
out.append(cur)
return [p.strip() for p in out if p.strip()]
PRIMARY = re.compile(r"^\s*(public|internal)\s+(sealed\s+|partial\s+|abstract\s+)*class\s+\w+(<[^>]*>)?\s*\(")
WIDE_AT = 6
wide = []
for f in CS_PROD:
all_lines = f.read_text(encoding="utf-8", errors="replace").splitlines()
for n, line in enumerate(all_lines, 1):
m = PRIMARY.search(line.split("//")[0])
if m and len(handed(parameters(all_lines, n - 1, m.end() - 1))) >= WIDE_AT:
wide.append(f"{rel(f)}:{n}")
R["wide_service_classes"] = {"count": len(wide), "list": wide}
Live from .github/quality.py, region constructor-width, read from this build at 99df7a8.
A split is by job, and the file that keeps the name lists its parts. The announcement the host
makes about its stores took seven things to do two jobs: attach the loggers, then say what came up.
Attaching is a type of its own, saying is another, and what is left is the order between them,
which is the only thing that was ever really a decision:
namespace TheYard.Api.Shared.Hosted;
public sealed class StoreAnnouncement(StoreLogAttachment attachment, StoreStartupLines lines) : IHostedService
{
public Task StartAsync(CancellationToken cancellationToken)
{
attachment.Attach();
lines.Write();
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
Live from api/TheYard.Api/Shared/Hosted/StoreAnnouncement.cs, region *, read from this build at 99df7a8.
A parameter object is sometimes the right answer, and it is not the same thing. Four of this
host's constructors were wide only because the four rings this process keeps were handed over one
at a time. The rings are one concern, named in a record's own title, and every answer those classes
give reads the rings and nothing else about them, so they travel as one collaborator now. That is
worth distinguishing out loud: grouping parameters that belong together removes the width, and
grouping parameters that have nothing to do with each other only hides it, which leaves a class
with the same several reasons to change and a tidier signature.
A third way: hand over the collaborator, not its parts. The performance proof's runner was
handed two ring buffers so it could build the type that measures one request out of them. Building
its own collaborator cost it two parameters and cost every test the chance to hand it another one,
so the collaborator arrives by constructor now and the two rings go to the type whose job they
are. That is not a parameter object: nothing was grouped, a class stopped doing a job that was
already somebody else's. The same move made room for a clock in all three classes this rung split,
each of which keeps an answer for a window and so has to be able to be told what time it is:
public async Task<object> GetRecentAsync(CancellationToken cancellation)
{
if (!Configured)
{
return new
{
configured = false,
note = "Application Insights is not configured for this build. It is wired at deploy time from Azure; a local run reports nothing.",
};
}
lock (_gate)
{
if (_cached is not null && clock.GetUtcNow() - _cachedAt < GoodFor)
{
return _cached;
}
}
return Keep(await source.AskAsync(cancellation));
}
Live from api/TheYard.Api/Shared/Observability/Telemetry.cs, region read, read from this build at 99df7a8.
Two things to know before splitting one. The compiler catches every new X(...) whose arity
changed, so the only break it cannot see is a type the service container activates by name: a part
split off a class and registered nowhere fails when something first asks for it, which on this
project meant a red gate on a store boot the shipping machine cannot run. And a class at exactly
five is one parameter from the line, so the clock or the token the next rung wants to hand it is
the parameter that makes it wide; the two rungs are worked in that order for that reason, and the
four classes that sat at five with a clock they could not be handed are where that order paid.
A file at the cap is cut by job, before anything is added to it
The same S, one line down: no production C# file runs past 300 lines, and no type does across all
of its parts (FileShapeTests). A cap alone is a cliff, so the ratchet counts the files within ten
lines of it, files_within_10_of_cap, which is the list of files whose next edit is the one that
would have to split them. The rule is to cut them at that point and not at the cliff, because the
edit that finds a file at 299 lines is never the edit that wants to think about its shape.
The cut follows a job, and the file that keeps the name keeps the decision. The request
pipeline had reached exactly 300 lines holding eleven middleware steps and the order between them.
The order is the only part of it that was ever a decision, so that is what the file kept; what every
answer is recorded and stamped with went to one file, and what a browser and the edge may keep went
to another:
if (identity.SiteName is { } siteName)
{
app.Use(async (context, next) =>
{
context.Response.OnStarting(() =>
{
context.Response.Headers[EdgeKeeps.SiteHeader] = siteName;
return Task.CompletedTask;
});
await next();
});
}
Live from api/TheYard.Api/Shared/Wiring/RequestRecording.cs, region site-header, read from this build at 99df7a8.
Where the pieces are not next to each other, the file that holds the order says so by calling
them separately. Two of those eleven steps sit on either side of the exception handler: the timing
outside it, so it records the status the caller actually got, and the error record directly inside
it, so it sees a failure in anything below. Gathering them into one call is tidier and wrong, and
the test that reads the error list said so within a minute of the first attempt.
The build holds the rings
A rule held by code review alone slips the first busy week. TheYard's is held by 19 tests that read
the compiled code with NetArchTest, a library that opens .NET assemblies (the compiled .dll files)
and checks which types use which. Reading compiled code matters: it sees method bodies and the hidden
types the compiler writes for lambdas and async methods, so a dependency tucked inside a lambda
fails the build as surely as a using line would. This repository uses the maintained fork,
NetArchTest.eNhancedEdition.
The first ten rules, each with what it stops, are a table in the record, under
How the build holds them. The rest came later, each
for a break it stops, and the record's addendum of 17 November names them all; the test file,
OnionTests.cs, is the list.
Each one was watched failing before it was trusted. Four failed against the code as it stood when
they were written:
- the two endpoint rules found
IServiceProvider in the account and admin handlers, and the bid
services in the bid, vehicle and admin handlers;
- the document store rule found the Cosmos DB adapter using the relational adapter's
DatabaseState;
- the database rule found three queries in the host, one of them in a lambda inside the composition
root.
The other six were proved by planting a forbidden reference and watching each go red. The whole file,
api/TheYard.Tests/OnionTests.cs:
using Mono.Cecil;
using NetArchTest.Rules;
using TheYard.Data;
using TheYard.Infrastructure;
namespace TheYard.Tests;
public sealed class OnionTests
{
private const string BaseClassLibrary = "System";
private const string CoverageTracker = "Coverlet.Core.Instrumentation";
private static readonly string[] TheDiskAndTheNetwork =
[
"System.IO.File", "System.IO.Directory", "System.IO.FileStream", "System.IO.StreamReader", "System.IO.StreamWriter",
"System.IO.FileInfo", "System.IO.DirectoryInfo", "System.IO.FileSystemInfo", "System.IO.Compression", "System.IO.MemoryMappedFiles", "System.IO.Pipes",
"System.Net", "System.Data",
];
private static readonly string[] TheMachine = ["System.Random", "System.TimeProvider", "System.Environment", "System.Diagnostics.Stopwatch", "System.Diagnostics.Process"];
[Fact]
public void Data_depends_on_nothing_outside_the_BCL()
{
var result = InRing(typeof(Vehicle), "TheYard.Data")
.ShouldNot().HaveDependencyOtherThan(BaseClassLibrary, CoverageTracker, "TheYard.Data")
.GetResult();
Assert.True(result.IsSuccessful, Explain(result));
var reaches = InRing(typeof(Vehicle), "TheYard.Data").ShouldNot().HaveDependencyOnAny([.. TheDiskAndTheNetwork, .. TheMachine]).GetResult();
Assert.True(reaches.IsSuccessful, Explain(reaches));
Assert.Empty(TypeLookups(typeof(Vehicle).Assembly.Location, "TheYard.Data"));
}
[Fact]
public void Data_has_no_behaviour()
{
Assert.Empty(Behaviour(typeof(Vehicle).Assembly.Location));
}
[Fact]
public void Domain_depends_on_nothing_outside_the_BCL_and_Data()
{
var result = InRing(typeof(BidRules), "TheYard.Domain")
.ShouldNot().HaveDependencyOtherThan(BaseClassLibrary, CoverageTracker, "TheYard.Data", "TheYard.Domain")
.GetResult();
Assert.True(result.IsSuccessful, Explain(result));
}
[Fact]
public void Application_depends_only_on_Domain_Data_and_the_BCL()
{
var result = InRing(typeof(StandingReader), "TheYard.Application")
.ShouldNot().HaveDependencyOtherThan(BaseClassLibrary, CoverageTracker, "TheYard.Data", "TheYard.Domain", "TheYard.Application")
.GetResult();
Assert.True(result.IsSuccessful, Explain(result));
}
[Fact]
public void Domain_never_reaches_the_disk_the_network_or_the_clock()
{
var result = InRing(typeof(BidRules), "TheYard.Domain")
.ShouldNot().HaveDependencyOnAny([.. TheDiskAndTheNetwork, .. TheMachine])
.GetResult();
Assert.True(result.IsSuccessful, Explain(result));
Assert.Empty(ClockReads(typeof(BidRules).Assembly.Location, "TheYard.Domain"));
Assert.Empty(TypeLookups(typeof(BidRules).Assembly.Location, "TheYard.Domain"));
}
[Fact]
public void Application_never_reaches_the_disk_or_the_network()
{
var result = InRing(typeof(StandingReader), "TheYard.Application")
.ShouldNot().HaveDependencyOnAny(TheDiskAndTheNetwork)
.GetResult();
Assert.True(result.IsSuccessful, Explain(result));
}
[Fact]
public void The_document_store_adapter_borrows_only_the_shared_user_from_the_relational_one()
{
string[] relational = typeof(YardDbContext).Assembly.GetTypes()
.Where(type => type.IsPublic && type != typeof(YardUser))
.Select(type => type.FullName!)
.Append("Microsoft.EntityFrameworkCore")
.Append("Microsoft.AspNetCore.Identity.EntityFrameworkCore")
.Append("Microsoft.Data")
.ToArray();
var result = Types.InAssembly(typeof(CosmosStore).Assembly)
.ShouldNot().HaveDependencyOnAny(relational)
.GetResult();
Assert.True(result.IsSuccessful, Explain(result));
}
[Fact]
public void Infrastructure_adapts_and_decides_nothing()
{
var found = new List<string>();
foreach (var adapter in new[] { typeof(YardDbContext).Assembly, typeof(CosmosStore).Assembly })
{
using var module = ModuleDefinition.ReadModule(adapter.Location);
found.AddRange(module.GetTypeReferences()
.Where(reference => reference.Namespace.StartsWith("Microsoft.AspNetCore", StringComparison.Ordinal) && !reference.Namespace.StartsWith("Microsoft.AspNetCore.Identity", StringComparison.Ordinal))
.Select(reference => $"{adapter.GetName().Name} uses {reference.FullName}"));
found.AddRange(MoneyDecisions(module));
}
Assert.True(found.Count == 0, string.Join(Environment.NewLine, found.Distinct()));
}
[Fact]
public void Endpoints_never_reach_a_store_or_the_service_container()
{
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()
{
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()
{
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()
{
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()
{
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()
{
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()
{
Assert.Empty(RuntimeLookups(typeof(Program).Assembly.Location));
}
[Fact]
public void A_route_or_a_handler_is_handed_its_settings_never_the_configuration()
{
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()
{
Assert.Empty(RuntimeLookups(typeof(TheYard.Application.Shared.Auction.StandingReader).Assembly.Location));
}
[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)));
}
[Fact]
public void The_host_opens_no_socket()
{
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));
}
private static List<string> RuntimeLookups(string assemblyPath)
{
using var module = ModuleDefinition.ReadModule(assemblyPath);
return [.. module.GetTypes()
.Where(type => !IsCompositionRoot(type) && !(type.Namespace ?? "").StartsWith(CoverageTracker, StringComparison.Ordinal))
.SelectMany(type => type.Methods.Where(method => method.HasBody))
.SelectMany(method => method.Body.Instructions
.Select(instruction => instruction.Operand)
.OfType<MethodReference>()
.Where(called => (called.DeclaringType.FullName, called.Name) is
("System.Environment", "GetEnvironmentVariable")
or ("System.IServiceProvider", "GetService")
or ("Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions", _)
or ("Microsoft.Extensions.DependencyInjection.ServiceProviderKeyedServiceExtensions", _)
or ("Microsoft.Extensions.DependencyInjection.ActivatorUtilities", _)
or ("Microsoft.AspNetCore.Http.HttpContext", "get_RequestServices")
or ("Microsoft.AspNetCore.Builder.WebApplication", "get_Configuration"))
.Select(called => $"{method.DeclaringType.FullName}.{method.Name} calls {called.DeclaringType.Name}.{called.Name}"))];
}
private static PredicateList InRing(Type marker, string ring) =>
Types.InAssembly(marker.Assembly).That().MeetCustomRule(type => InNamespace(Outermost(type).Namespace, ring));
private static List<string> ClockReads(string assemblyPath, string ring)
{
using var module = ModuleDefinition.ReadModule(assemblyPath);
return [.. module.GetTypes()
.Where(type => InNamespace(Outermost(type).Namespace, ring))
.SelectMany(type => type.Methods.Where(method => method.HasBody))
.SelectMany(method => method.Body.Instructions
.Select(instruction => instruction.Operand)
.OfType<MethodReference>()
.Where(called => called.DeclaringType.FullName is "System.DateTime" or "System.DateTimeOffset"
&& called.Name is "get_Now" or "get_UtcNow" or "get_Today")
.Select(called => $"{method.DeclaringType.FullName}.{method.Name} reads {called.DeclaringType.Name}.{called.Name[4..]}"))];
}
private static List<string> TypeLookups(string assemblyPath, string ring)
{
using var module = ModuleDefinition.ReadModule(assemblyPath);
return [.. module.GetTypes()
.Where(type => InNamespace(Outermost(type).Namespace, ring))
.SelectMany(type => type.Methods.Where(method => method.HasBody))
.SelectMany(method => method.Body.Instructions
.Select(instruction => instruction.Operand)
.OfType<MethodReference>()
.Where(called => (called.DeclaringType.FullName == "System.Type" && called.Name == "GetType" && called.Parameters.Count > 0)
|| (called.DeclaringType.FullName == "System.Reflection.Assembly" && called.Name.StartsWith("Load", StringComparison.Ordinal))
|| called.DeclaringType.FullName == "System.Activator")
.Select(called => $"{method.DeclaringType.FullName}.{method.Name} calls {called.DeclaringType.Name}.{called.Name}"))];
}
private static readonly HashSet<string> RecordMembers = ["ToString", "PrintMembers", "Equals", "GetHashCode", "<Clone>$", "Deconstruct", "op_Equality", "op_Inequality", "get_EqualityContract"];
private static List<string> Behaviour(string assemblyPath)
{
using var module = ModuleDefinition.ReadModule(assemblyPath);
return [.. module.GetTypes()
.Where(type => InNamespace(Outermost(type).Namespace, "TheYard.Data") && !type.CustomAttributes.Any(IsCompilerGenerated))
.SelectMany(type => type.Methods.Where(method => method.HasBody))
.Where(method => !method.IsGetter && !method.IsSetter && !method.IsConstructor && !RecordMembers.Contains(method.Name) && !method.CustomAttributes.Any(IsCompilerGenerated))
.Select(method => $"{method.DeclaringType.FullName}.{method.Name} is behaviour in Data")];
}
private static bool IsCompilerGenerated(CustomAttribute attribute) =>
attribute.AttributeType.FullName == "System.Runtime.CompilerServices.CompilerGeneratedAttribute";
private static readonly System.Text.RegularExpressions.Regex Money = new("^(amount|bid|buyNow|price|reserve|increment|minNextBid|currentBid|startingBid)$", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
private static readonly HashSet<Mono.Cecil.Cil.Code> Comparisons =
[
Mono.Cecil.Cil.Code.Clt, Mono.Cecil.Cil.Code.Clt_Un, Mono.Cecil.Cil.Code.Cgt, Mono.Cecil.Cil.Code.Cgt_Un,
Mono.Cecil.Cil.Code.Blt, Mono.Cecil.Cil.Code.Blt_S, Mono.Cecil.Cil.Code.Blt_Un, Mono.Cecil.Cil.Code.Blt_Un_S,
Mono.Cecil.Cil.Code.Bgt, Mono.Cecil.Cil.Code.Bgt_S, Mono.Cecil.Cil.Code.Bgt_Un, Mono.Cecil.Cil.Code.Bgt_Un_S,
Mono.Cecil.Cil.Code.Ble, Mono.Cecil.Cil.Code.Ble_S, Mono.Cecil.Cil.Code.Ble_Un, Mono.Cecil.Cil.Code.Ble_Un_S,
Mono.Cecil.Cil.Code.Bge, Mono.Cecil.Cil.Code.Bge_S, Mono.Cecil.Cil.Code.Bge_Un, Mono.Cecil.Cil.Code.Bge_Un_S,
];
private static IEnumerable<string> MoneyDecisions(ModuleDefinition module) =>
module.GetTypes()
.SelectMany(type => type.Methods.Where(method => method.HasBody))
.Where(method => method.Body.Instructions.Any(instruction => Comparisons.Contains(instruction.OpCode.Code)))
.Where(method => method.Parameters.Any(parameter => Money.IsMatch(parameter.Name))
|| method.Body.Instructions.Select(instruction => instruction.Operand).OfType<MethodReference>()
.Any(called => called.DeclaringType.FullName == "TheYard.Data.Vehicle" && called.Name is "get_CurrentBid" or "get_BuyNowPrice" or "get_ReservePrice" or "get_StartingBid"))
.Select(method => $"{method.DeclaringType.FullName}.{method.Name} decides on money in an adapter");
private static bool InNamespace(string name, string ring) =>
name == ring || name.StartsWith(ring + ".", StringComparison.Ordinal);
private static bool IsPartOfAnEndpointClass(TypeDefinition type)
{
var outer = Outermost(type);
return !IsCompositionRoot(outer) && (outer.Name.EndsWith("Endpoints", StringComparison.Ordinal) || RouteMappers.Value.Contains(outer.FullName));
}
private static readonly Lazy<HashSet<string>> RouteMappers = new(() =>
{
using var module = ModuleDefinition.ReadModule(typeof(Program).Assembly.Location);
return module.GetTypes()
.Where(type => type.Methods.Any(method => method.HasBody && method.Body.Instructions
.Select(instruction => instruction.Operand).OfType<MethodReference>()
.Any(called => called.DeclaringType.Name.EndsWith("EndpointRouteBuilderExtensions", StringComparison.Ordinal) && called.Name.StartsWith("Map", StringComparison.Ordinal))))
.Select(type => Outermost(type).FullName)
.ToHashSet(StringComparer.Ordinal);
});
private static readonly HashSet<string> CompositionRoot =
[
"Program", "<Program>$",
"ActivityRegistration", "AdminRegistration", "ApiRegistration", "AuthRegistration", "CostRegistration", "HostedSiteRegistration",
"ObservabilityRegistration", "SpaRegistration", "StartupRegistration", "StoreRegistration", "TelemetryRegistration", "UsageRegistration",
"Modules", "IModule",
"RequestPipeline", "HostedSiteMount", "ShedApplication",
];
private static bool IsCompositionRoot(TypeDefinition type)
{
var outer = Outermost(type);
return CompositionRoot.Contains(outer.Name)
|| (outer.Name == "Module" && (outer.Namespace ?? "").StartsWith("TheYard.Api.Features.", StringComparison.Ordinal));
}
private static TypeDefinition Outermost(TypeDefinition type)
{
while (type.DeclaringType is { } outer)
{
type = outer;
}
return type;
}
private static string Explain(TestResult result) =>
result.IsSuccessful
? ""
: string.Join(Environment.NewLine, (result.FailingTypes ?? []).Select(type => $"{type.FullName}: {type.Explanation}"));
}
Live from api/TheYard.Tests/OnionTests.cs, region *, read from this build at 99df7a8.
Watch one go red on your own repository
- Add the package to your test project:
dotnet add <your test project> package NetArchTest.eNhancedEdition.
- Write one rule: your Domain project may depend on
System and on itself, and nothing else (the test is below).
- Run
dotnet test and watch it pass.
- Plant a forbidden reference: add
Microsoft.Extensions.Logging.Abstractions to the Domain project and write _ = Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance; in any Domain method.
- Run
dotnet test again: it fails and names the type and the dependency it found. Delete the line, and keep the test.
using NetArchTest.Rules;
using Xunit;
public sealed class OnionTests
{
[Fact]
public void Domain_depends_on_nothing_outside_the_BCL()
{
var result = Types.InAssembly(typeof(YourApp.Domain.SomeRule).Assembly)
.ShouldNot().HaveDependencyOtherThan("System", "YourApp.Domain")
.GetResult();
Assert.True(
result.IsSuccessful,
string.Join(Environment.NewLine, (result.FailingTypes ?? []).Select(type => $"{type.FullName}: {type.Explanation}")));
}
}
If your continuous integration collects code coverage, add "Coverlet.Core.Instrumentation" to the
allowed list: the coverage tool writes a tracker into every assembly it measures, and the rule would
otherwise fail on code nobody wrote.
One project, rings as folders
Folders can draw the rings as well as projects can. The Shed, a file and folder browser that lives
beside TheYard in this repository
(samples/theshed) and runs at
theshed.stevenstout.biz, is one project. Its rings are folders, each folder is a namespace, and the
tests select a ring by namespace instead of by project: Data, Domain, Application,
Infrastructure, Controllers, Documentation and Composition. The reasoning for keeping it to one
project is its own record,
One project, seven folders, dependencies inward.
One project costs one thing. Across projects, the compiler refuses a reference that would make a
cycle, so an adapter can never use the host and nobody has to test it. Inside one project the compiler
allows anything, so every direction is a test's job, and so is a type that lands in a folder no rule
names. The last test in the file below exists for exactly that: a new folder or a missing namespace
line would otherwise be checked by none of the rules.
The practice: in a small codebase, start with folders and these tests, and split a ring into a
project of its own the day a second store or a second host appears. This is the section to copy first.
The Shed's tests, whole,
samples/theshed/tests/TestProject.Tests/OnionTests.cs:
using Mono.Cecil;
using NetArchTest.Rules;
using TestProject.Domain;
namespace TestProject.Tests;
public sealed class OnionTests
{
private const string Coverage = "Coverlet.Core.Instrumentation";
private static readonly string[] DataMayUse = ["System", Coverage, "TestProject.Data"];
private static readonly string[] DomainMayUse = ["System", Coverage, "TestProject.Data", "TestProject.Domain"];
private static readonly string[] ApplicationMayUse = ["System", Coverage, "TestProject.Data", "TestProject.Domain", "TestProject.Application"];
private static readonly string[] InfrastructureMustNotUse = ["TestProject.Controllers", "TestProject.Composition", "TestProject.Documentation", "Microsoft.AspNetCore"];
private static readonly string[] TheDisk = ["System.IO.File", "System.IO.Directory", "System.IO.FileInfo", "System.IO.DirectoryInfo", "System.IO.FileStream", "System.IO.FileSystemInfo", "System.IO.StreamReader", "System.IO.StreamWriter"];
private static readonly string[] ControllersMustNotUse = [.. TheDisk, "TestProject.Infrastructure", "TestProject.Composition", "TestProject.Application.IFileStore", "TestProject.Domain.HomePath", "Microsoft.AspNetCore.Mvc.PhysicalFileResult"];
private static readonly string[] DocumentationMustNotUse = ["TestProject.Controllers", "TestProject.Composition", "TestProject.Infrastructure", "Microsoft.AspNetCore"];
private static readonly string[] Registration = ["Microsoft.Extensions.DependencyInjection.IServiceCollection", "Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions"];
[Fact]
public void Data_depends_on_nothing_outside_the_BCL() =>
AssertHolds(InRing("TestProject.Data").ShouldNot().HaveDependencyOtherThan(DataMayUse).GetResult());
[Fact]
public void Domain_depends_on_nothing_outside_the_BCL_and_Data() =>
AssertHolds(InRing("TestProject.Domain").ShouldNot().HaveDependencyOtherThan(DomainMayUse).GetResult());
[Fact]
public void Application_depends_only_on_Domain_Data_and_the_BCL() =>
AssertHolds(InRing("TestProject.Application").ShouldNot().HaveDependencyOtherThan(ApplicationMayUse).GetResult());
[Fact]
public void Application_never_touches_the_disk_itself() =>
AssertHolds(InRing("TestProject.Application").ShouldNot().HaveDependencyOnAny(TheDisk).GetResult());
[Fact]
public void Infrastructure_depends_on_nothing_outside_it() =>
AssertHolds(InRing("TestProject.Infrastructure").ShouldNot().HaveDependencyOnAny(InfrastructureMustNotUse).GetResult());
[Fact]
public void Controllers_never_touch_the_disk_or_the_file_store() =>
AssertHolds(InRing("TestProject.Controllers").ShouldNot().HaveDependencyOnAny(ControllersMustNotUse).GetResult());
[Fact]
public void Documentation_reaches_only_Data_and_the_framework() =>
AssertHolds(InRing("TestProject.Documentation").ShouldNot().HaveDependencyOnAny(DocumentationMustNotUse).GetResult());
[Fact]
public void Services_are_registered_only_in_Composition() =>
AssertHolds(Types.InAssembly(typeof(HomePath).Assembly)
.That().MeetCustomRule(type => Outermost(type).Namespace != "TestProject.Composition")
.ShouldNot().HaveDependencyOnAny(Registration)
.GetResult());
[Fact]
public void Every_type_sits_in_one_of_the_folders_the_rings_name()
{
using var module = ModuleDefinition.ReadModule(typeof(HomePath).Assembly.Location);
var strays = module.Types
.Where(type => !type.Name.StartsWith('<'))
.Where(type => !type.Namespace.StartsWith("System", StringComparison.Ordinal) && !type.Namespace.StartsWith("Microsoft", StringComparison.Ordinal) && !type.Namespace.StartsWith("Coverlet", StringComparison.Ordinal))
.Where(type => type.Namespace != "TestProject" && !Folders.Any(ring => InNamespace(type.Namespace, ring)))
.Select(type => type.FullName)
.ToList();
Assert.True(strays.Count == 0, "outside every ring: " + string.Join(", ", strays));
}
private static readonly string[] Folders = ["TestProject.Data", "TestProject.Domain", "TestProject.Application", "TestProject.Infrastructure", "TestProject.Controllers", "TestProject.Documentation", "TestProject.Composition"];
private static PredicateList InRing(string ring) =>
Types.InAssembly(typeof(HomePath).Assembly).That().MeetCustomRule(type => InNamespace(Outermost(type).Namespace, ring));
private static bool InNamespace(string name, string ring) =>
name == ring || name.StartsWith(ring + ".", StringComparison.Ordinal);
private static TypeDefinition Outermost(TypeDefinition type)
{
while (type.DeclaringType is { } outer)
{
type = outer;
}
return type;
}
private static void AssertHolds(TestResult result) =>
Assert.True(
result.IsSuccessful,
string.Join(Environment.NewLine, (result.FailingTypes ?? []).Select(type => $"{type.FullName}: {type.Explanation}")));
}
Live from samples/theshed/tests/TestProject.Tests/OnionTests.cs, region *, read from this build at 99df7a8.
When not to build it this way
The rings cost projects, interfaces and tests, and they pay that back only when there is something to
protect: here, two stores behind the same rules, a host with an operator's tab, and rules worth
testing on their own. A small service over one table, a spike written to learn something quickly, or
a script that reads, changes and writes is clearer flat, and gains a ring the day a second store or a
rule worth testing alone turns up. The record draws that line in more detail, under
When not to build it this way,
and The Shed above is the middle road between the two.