.NET Core / Web API71 min total · 19 parts
Building REST APIs with ASP.NET Core: Routing, Middleware, and Dependency Injection
Part 2 of 19 · ~1 min
The Minimal Hosting Model and Program.cs
Here's the entire first version of Bench, written in an afternoon before either Dana or Theo had touched a real database:
var builder = WebApplication.CreateBuilder(args);
// Registering services with the DI container happens here, before Build()
builder.Services.AddControllers();
var app = builder.Build();
// Configuring the middleware pipeline happens here, after Build()
app.MapControllers();
app.Run();
Four lines that actually do something, and they fall cleanly into two halves. WebApplicationBuilder — what CreateBuilder hands back — is where you populate the dependency injection container: every builder.Services.Add... call between here and Build() registers something the framework will later know how to construct on request. Build() is the hinge. Everything after it is WebApplication, the actual running app, and from here on you're wiring up the middleware pipeline instead — app.Use..., app.Map... — the chain of steps a request actually flows through.
Try to sneak a service registration in after Build() — app.Services.AddScoped<ToolRepository>() — and it won't compile. WebApplication.Services is an IServiceProvider, built and frozen the moment Build() ran; the Add... extension methods only exist on IServiceCollection, which is what builder.Services was. Once you've called Build(), that door isn't propped open a crack — it's a different type entirely, and the registration surface is simply gone.
Dana found this out the annoying way three weeks in, trying to register AppDbContext inside an if (app.Environment.IsDevelopment()) block she'd absent-mindedly placed after var app = builder.Build();. The fix wasn't a workaround — it was moving four lines up, above Build(), which is the entire lesson: the split isn't a style convention you can bend, it's two different objects with two different jobs, and the compiler is the one enforcing it.