Lesson 1 of 9 · 24m
Minimal APIs and the Discipline of the Composition Root
Structure modern .NET services around explicit route composition, endpoint metadata, and small testable handlers instead of controller-era ceremony.
A team I inherited once had a 'simple' minimal API where Program.cs was 1,800 lines long. Every feature began as five lines, nobody created a boundary, and six months later the composition root had become a junk drawer. Minimal APIs are not an excuse to skip architecture. They are a way to make the architecture visible without paying controller ceremony for every endpoint.
Start with explicit composition
Program.cs should wire the application, not implement the business. Keep the top-level statements short enough to read in one screen:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<IOrderService, OrderService>();
var app = builder.Build();
app.UseExceptionHandler();
app.MapOrderEndpoints();
app.Run();The endpoint mapping lives beside the feature:
public static class OrderEndpoints
{
public static RouteGroupBuilder MapOrderEndpoints(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/orders").WithTags("Orders");
group.MapGet("/{id:guid}", GetOrder).RequireAuthorization();
group.MapPost("", CreateOrder).RequireAuthorization("orders.write");
return group;
}
private static async Task<Results<Ok<OrderDto>, NotFound>> GetOrder(
Guid id,
IOrderService orders,
CancellationToken ct)
{
var order = await orders.FindAsync(id, ct);
return order is null ? TypedResults.NotFound() : TypedResults.Ok(order);
}
}This style scales because each feature owns its routes, authorization, validation, and response shapes. The application entry point remains a map rather than a landfill.
Endpoints are not application services
A minimal endpoint is an adapter. It translates HTTP into a use case call and translates the result back into HTTP. It should not contain transaction orchestration, complex domain branching, or raw SQL unless the endpoint is intentionally a thin query endpoint. The old controller rule still applies: transport decisions at the edge, business decisions in the core.
Typed results are documentation that compiles
Prefer TypedResults and union-style Results<...> signatures when practical. They make the response contract visible and improve OpenAPI generation:
private static async Task<Results<Created<OrderDto>, ValidationProblem>> CreateOrder(
CreateOrderRequest request,
IOrderService orders,
CancellationToken ct)
{
if (request.Lines.Count == 0)
return TypedResults.ValidationProblem(new Dictionary<string, string[]>
{
["lines"] = ["At least one order line is required."]
});
var order = await orders.CreateAsync(request, ct);
return TypedResults.Created($"/orders/{order.Id}", order);
}The signature tells the next engineer what can happen without forcing them to inspect every branch.
Middleware order still matters
UseExceptionHandler, authentication, authorization, rate limiting, output caching, CORS, and endpoint mapping are not decorative. Their order defines what runs inside which boundary. Put exception handling early, CORS before endpoints that need it, authentication before authorization, and endpoint-specific metadata on the route or group rather than duplicating it manually.
Field notes
MapGetreturning200in a local test does not mean the endpoint publishes accurate metadata; inspect generated OpenAPI before clients depend on it.- Do not inject
HttpContextinto domain services. It drags transport concerns through the entire object graph. - Route constraints such as
{id:guid}reject malformed input before your handler runs; use them deliberately. - Minimal APIs remove boilerplate, not responsibility. If the endpoint file needs scrolling, extract the use case.
Was this lesson helpful?