Delete a Box: Reviewing an Agent-Generated .NET Architecture

On Wednesday I posted a short story about Johny, an architect whose diagrams got smaller every year until a junior vibe coded the fourteen-box version in an afternoon. A few people asked what reviewing that afternoon's work looks like in code. This article answers that.

The sample below is a composite, like Johny. It's the shape I keep running into when an agent is asked for something "scalable", cut down to one feature so it fits on a page: placing an order and charging a card. Every snippet compiles on .NET 10, and the retry numbers further down come from a run on my machine.

The whole review comes down to one question per box: what breaks if this isn't here?

The order service, as generated

The request goes into an endpoint, which publishes a PlaceOrder message to an in-process bus. A handler picks it up in the same process, saves the order through a generic repository, asks a factory for a payment provider, charges the card through an HttpClient with a resilience handler, and publishes OrderPlaced for nobody in particular. An outbox table and a saga sit next to it, waiting for a second service that doesn't exist yet.

Here's the handler, which is where the boxes meet:

public sealed class PlaceOrderHandler(
    IRepository<Order> orders,
    IPaymentProviderFactory payments,
    IMessageBus bus) : IHandle<PlaceOrder>
{
    public async Task HandleAsync(PlaceOrder message, CancellationToken ct)
    {
        var order = new Order { Id = message.OrderId, CustomerId = message.CustomerId, Total = message.Total };
        await orders.AddAsync(order, ct);
        await orders.SaveChangesAsync(ct);

        var paid = await payments.Create("acmepay").ChargeAsync(order.Id, order.Total, ct);
        order.Status = paid ? OrderStatus.Paid : OrderStatus.PaymentFailed;
        await orders.SaveChangesAsync(ct);

        await bus.PublishAsync(new OrderPlaced(order.Id), ct);
    }
}

It reads well. Each type has one job, every dependency is an interface, and there's a test project with a mock for each of them. None of that tells you whether the boxes need to exist, so we go through them one at a time.

Box 1: the generic repository

public interface IRepository<T> where T : class
{
    Task<T?> GetByIdAsync(Guid id, CancellationToken ct);
    Task AddAsync(T entity, CancellationToken ct);
    Task SaveChangesAsync(CancellationToken ct);
}

public sealed class EfRepository<T>(ShopDbContext db) : IRepository<T> where T : class
{
    public Task<T?> GetByIdAsync(Guid id, CancellationToken ct) => db.Set<T>().FindAsync([id], ct).AsTask();
    public async Task AddAsync(T entity, CancellationToken ct) => await db.Set<T>().AddAsync(entity, ct);
    public Task SaveChangesAsync(CancellationToken ct) => db.SaveChangesAsync(ct);
}

What breaks without it? Nothing. DbSet<T> is already the repository and DbContext is already the unit of work, and Microsoft's own persistence guidance says so. Every method here forwards to EF Core under a new name. The usual defence is testing, but a mocked IRepository<Order> tests that you called AddAsync, not that the order was saved. A real database in a container tests the second thing (Testcontainers with PostgreSQL).

Verdict: delete. I covered when a repository does pay rent (aggregates with real invariants, Dapper, messy legacy data access) in Repository Pattern in .NET: When It Pays Rent. A generic IRepository<T> over EF Core never made that list.

Box 2: a factory for one payment provider

public sealed class PaymentProviderFactory(IServiceProvider services) : IPaymentProviderFactory
{
    public IPaymentProvider Create(string name) => name switch
    {
        "acmepay" => services.GetRequiredService<AcmePayProvider>(),
        _ => throw new NotSupportedException($"Unknown payment provider '{name}'.")
    };
}

What breaks without it? Nothing today. There's one provider and the handler passes a hard-coded "acmepay", so the factory always returns the same object. It also moved a missing registration from startup to the first payment, because GetRequiredService now runs inside a request.

Verdict: delete, and inject the client directly. When a second provider arrives, the container already does this job. Keyed services have been built in since .NET 8:

services.AddKeyedScoped<IPaymentProvider, AcmePayProvider>("acmepay");

// at the call site
([FromKeyedServices("acmepay")] IPaymentProvider pay) => ...

That's one registration line when you need it, not a type you maintain from day one.

Box 3: the in-process bus, the outbox and the saga

What breaks without it? This one deserves a slower answer, because it's covering for a real failure. The handler writes the order, calls the provider, then writes again. If the process dies between the first save and the charge, you're left with an order in Pending that nobody will ever charge.

But the bus doesn't fix that. The handler runs in the same process, with the same DbContext, doing the same two writes in the same order. Publishing a message to yourself adds a hop and moves the stack trace somewhere else. OrderPlaced has no subscriber, and the saga coordinates one step.

Verdict: delete the bus and the saga. Answer the real failure with the smallest thing that makes it visible: a status column and a query.

app.MapGet("/orders/stuck", (ShopDbContext db) =>
    db.Orders.Where(o => o.Status == OrderStatus.Pending && o.CreatedAt < DateTime.UtcNow.AddMinutes(-5)).ToListAsync());

Whether that query runs in a hosted service, an alert or someone's Monday dashboard is a decision for the ADR, not for the agent. The outbox comes back the day a second process has to learn about OrderPlaced, and at that point it pays for itself. I wrote about it in the Outbox pattern in .NET.

Box 4: the retry policy, the box that stays

builder.Services.AddHttpClient<AcmePayClient>(c => c.BaseAddress = new Uri("https://api.acmepay.example/"))
    .AddStandardResilienceHandler();

What breaks without it? A lot. Payment providers return the odd 503, and without retries each one becomes a failed order and a support ticket. So this box answers the question, and it stays.

It's also the most dangerous line in the sample. The standard resilience handler retries every HTTP method by default, POST included. A charge is a POST, and a gateway timeout doesn't tell you whether the card was charged.

I measured it. A fake provider records a charge for every request, then answers 504 Gateway Timeout, the way a provider behaves when it charges the card and the response gets lost on the way back. I ran three configurations, each with the defaults from Microsoft.Extensions.Http.Resilience:

Configuration Requests sent Charges recorded
AddStandardResilienceHandler() 4 4
+ o.Retry.DisableForUnsafeHttpMethods() 1 1
Retries on, Idempotency-Key header sent 4 1

One click on "Pay", four charges. The default retry makes three more attempts with exponential backoff, which took about ten seconds in my run, and each attempt reached the provider.

Verdict: keep the retry, fix what it's allowed to repeat. You have two options:

  1. Send an idempotency key if your provider supports one (Stripe and several others accept an Idempotency-Key header). The provider deduplicates, so retries become safe. In my fake provider the key collapses four requests into one charge, which is what a provider that honours the header does. Check yours before you rely on it.
  2. Turn retries off for unsafe methods if it doesn't: o.Retry.DisableForUnsafeHttpMethods() (namespace Microsoft.Extensions.Http.Resilience). A failed charge then shows up as PaymentFailed, and a person decides.

The order id works well as the key because it already exists and stays the same for the whole order:

public sealed class AcmePayClient(HttpClient http)
{
    public async Task<bool> ChargeAsync(Guid orderId, decimal amount, CancellationToken ct)
    {
        using var request = new HttpRequestMessage(HttpMethod.Post, "charges")
        {
            Content = JsonContent.Create(new { amount, currency = "EUR" })
        };
        request.Headers.Add("Idempotency-Key", orderId.ToString());

        using var response = await http.SendAsync(request, ct);
        return response.IsSuccessStatusCode;
    }
}

I went into the retry, timeout and circuit-breaker defaults in more depth in HTTP Resilience in .NET (Part 1).

The order service, after the review

builder.Services.AddDbContext<ShopDbContext>(o => o.UseSqlite("Data Source=shop.db"));
builder.Services.AddHttpClient<AcmePayClient>(c => c.BaseAddress = new Uri("https://api.acmepay.example/"))
    .AddStandardResilienceHandler();

var app = builder.Build();

app.MapPost("/orders", async (PlaceOrderRequest req, ShopDbContext db, AcmePayClient pay, CancellationToken ct) =>
{
    var order = new Order { Id = Guid.CreateVersion7(), CustomerId = req.CustomerId, Total = req.Total };
    db.Orders.Add(order);
    await db.SaveChangesAsync(ct);

    order.Status = await pay.ChargeAsync(order.Id, order.Total, ct) ? OrderStatus.Paid : OrderStatus.PaymentFailed;
    await db.SaveChangesAsync(ct);

    return TypedResults.Created($"/orders/{order.Id}", new { order.Id, order.Status });
});

The app, the database and the provider are still there. The retry stayed, and it now sends a key with every charge. The crash between the two saves is still possible, but now it shows up on a query instead of hiding behind a bus. Everything else went.

Box What breaks without it Verdict
Generic repository Nothing Delete
Payment provider factory Nothing, until a second provider (keyed services) Delete
In-process bus + saga Nothing it actually prevented Delete
Outbox Nothing until a second process subscribes Delete, add back then
Retry policy Transient 503s become failed orders Keep, with an idempotency key
Pending status + stuck query Crash between save and charge goes unseen Add

The review added one box. That's normal: asking "what breaks?" finds failures, and sometimes the honest answer is a small new piece instead of a big old one.

Keep the boxes deleted

A box you delete in review comes back in the next prompt unless something stops it. I use three things, from cheapest to strictest.

Write the decision down. An Architecture Decision Record takes five minutes and saves arguing the same point every sprint:

# ADR 007: No message bus inside the order service


Status: Accepted (2026-12-04)

Context: Order placement runs in one process against one database.
OrderPlaced has no subscriber.

Decision: Call the payment provider directly from the endpoint, with an
idempotency key. Track unfinished orders with a Pending status and a query.

Revisit when: a second process needs to react to OrderPlaced. Then add
an outbox, not an in-process bus.

Tell the agent. The agent reads your instructions file before it writes anything, so put the decisions there. A few lines in .github/copilot-instructions.md:

## Architecture constraints

- One process, one database. Don't add a message bus, saga or outbox without an ADR.
- Use DbContext directly. Don't wrap EF Core in a generic repository.
- No factory or interface with a single implementation. Use keyed services when a second one exists.
- Every outbound POST either sends an idempotency key or disables retries for unsafe methods.
- Decisions live in docs/adr/. Read them before proposing structure.

Fail the build. Instructions are a request. An architecture test is a gate the agent has to pass, and it reads the failure message like any other compiler error. I showed how to set that up with NetArchTest in Architecture Tests: The Guardrail Your AI Agent Can't Talk Around.

The review checklist

Save this for the next pull request where a model drew the diagram:

  • For each new type: what breaks if it isn't here? If the answer is "nothing yet", delete it.
  • Does any interface have exactly one implementation and no test that needs a second?
  • Does a message leave the process? If not, why is there a bus?
  • Which outbound calls are POST, PUT or DELETE, and what happens when each one is retried?
  • Is there a failure the new structure hides instead of handling? Make it visible with a status and a query.
  • Is the decision written down where the next agent will read it?

The agent writes the fourteen-box version in an afternoon. You still have to review it, and most of reviewing is deleting.

Further reading