CodeOath
← All posts
.NET Core / Web API70 min total · 19 parts

Building REST APIs with ASP.NET Core: Routing, Middleware, and Dependency Injection

Contents — Part 2 of 19: The Minimal Hosting Model and Program.cs
Part 2 of 19 · ~1 min

The Minimal Hosting Model and Program.cs

Modern ASP.NET Core (from .NET 6 onward) uses a single top-level Program.cs file instead of the older split Program/Startup classes — functionally equivalent, just less ceremony:

var builder = WebApplication.CreateBuilder(args);

// Registering services with the DI container happens here, before Build()
builder.Services.AddControllers();
builder.Services.AddScoped<IOrderService, OrderService>();

var app = builder.Build();

// Configuring the middleware pipeline happens here, after Build()
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

app.Run();

WebApplicationBuilder separates two distinct phases: service registration (builder.Services.Add..., populating the DI container that will construct your controllers and their dependencies) happens before Build(); middleware configuration (app.Use..., app.Map..., building the pipeline a request actually flows through) happens after. Mixing these up — trying to register a service after Build(), for instance — is a compile-time or runtime error depending on exactly what's attempted, because WebApplication (returned by Build()) no longer exposes the same service-registration surface as WebApplicationBuilder.