skip to content

WebApplicationBuilder & Program.cs

WebApplication.CreateBuilder, the builder's Services, Configuration and Environment, then Build and Run in Program.cs, and leaving the Startup class. Interviewers probe the minimal hosting model.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

5

In an ASP.NET Core 10 Program.cs, what do WebApplication.CreateBuilder(args), builder.Build() and app.Run() each do?

level: juniorimportance: must knowfreq 76%

answer

  1. two phases: builder, then app
  2. Services, Configuration, Environment, Host, WebHost
  3. Build seals the service collection
  4. WebApplication: IHost + IApplicationBuilder + IEndpointRouteBuilder
  5. Run blocks, RunAsync returns Task

basics

~20 s

CreateBuilder makes a WebApplicationBuilder with default configuration, logging, Kestrel and DI; Build turns the registered services into a provider and returns a WebApplication for the pipeline and endpoints; Run starts the server and blocks until shutdown.

solid answer

~40 s

`WebApplication.CreateBuilder(args)` returns a `WebApplicationBuilder` that already has configuration loaded (appsettings files, user secrets in Development, environment variables, command-line args), console/debug/event-source logging, Kestrel with IIS integration, routing services and host filtering. You register services on `builder.Services` and read `builder.Configuration` and `builder.Environment`. `builder.Build()` builds the `IServiceProvider`, makes the service collection read-only and returns a `WebApplication` — an `IHost`, an `IApplicationBuilder` for middleware and an `IEndpointRouteBuilder` for `MapGet` and friends. It can be called once. `app.Run()` starts the host — hosted services, then Kestrel binding its addresses — and blocks the calling thread until shutdown; `RunAsync()` returns a `Task` instead. In Development the builder also turns on DI scope validation and `ValidateOnBuild`.

code

csharp · 13 lines
csharp
var builder = WebApplication.CreateBuilder(args);

// Phase 1: what exists
builder.Services.AddProblemDetails();
var clinicDb = builder.Configuration.GetConnectionString("Clinic");

var app = builder.Build();   // provider built, Services now read-only

// Phase 2: how a request flows
app.UseHttpsRedirection();
app.MapGet("/health/ping", () => "pong");

app.Run();                   // blocks until shutdown

go deeper

for a junior

Recall the three calls in order: CreateBuilder for services and settings, Build for the app, Run to start listening, and that registrations go above Build.

for a middle

Explain what CreateBuilder configures by default, why the service collection is read-only after Build, and what WebApplication's three interfaces let you do.

for a senior

Diagnose startup failures from late registrations or scope validation in Development, and choose Run, RunAsync or StartAsync for the hosting situation.

for a principal

Decide how much of startup belongs in Program.cs versus extension methods per module, so a growing service keeps one readable composition root.

## Two phases in one file The **minimal hosting model**, introduced in ASP.NET Core 6 and still the shape of every .NET 10 template, splits `Program.cs` into two phases joined by one call: 1. **Configure the builder** — `var builder = WebApplication.CreateBuilder(args);` then register services and read settings. 2. **Configure the app** — `var app = builder.Build();` then add middleware and map endpoints. 3. **Run** — `app.Run();` starts everything and waits. Everything before `Build()` is about *what exists* (services, configuration, server settings); everything after it is about *how a request flows* (middleware and endpoints). ## What CreateBuilder sets up `CreateBuilder` wraps a `HostApplicationBuilder` (the Generic Host's builder) and applies web defaults on top. Out of the box you get: - **Content root** set to the current directory, and the web root `wwwroot` under it; - **host configuration** from `ASPNETCORE_`- and `DOTNET_`-prefixed environment variables and the command-line args; - **app configuration** from `appsettings.json`, `appsettings.{Environment}.json`, user secrets in Development, environment variables and the command line; - **logging** to the console, debug output and EventSource (plus the Event Log on Windows), filtered by the `Logging` section; - **Kestrel** configured from the `Kestrel` configuration section, plus IIS in-process and out-of-process integration; - **routing services**, **host filtering** driven by `AllowedHosts`, and static web assets in Development; - in Development, a service provider built with **`ValidateScopes`** and **`ValidateOnBuild`**, so a singleton that captures a scoped service fails fast. The builder exposes these as properties: | Property | Type | Used for | |---|---|---| | `Services` | `IServiceCollection` | Registering services | | `Configuration` | `ConfigurationManager` | Reading settings now and adding sources | | `Environment` | `IWebHostEnvironment` | `IsDevelopment()`, content root, web root | | `Logging` | `ILoggingBuilder` | Logging providers and filters | | `Host` | `ConfigureHostBuilder` | `IHostBuilder` extension methods from libraries | | `WebHost` | `ConfigureWebHostBuilder` | Server settings such as Kestrel options | Because `Configuration` is a `ConfigurationManager`, a value such as `builder.Configuration.GetConnectionString("Clinic")` can be read **before** `Build()` — the old `Startup` constructor's job. ## What Build does `builder.Build()` is the hinge: - it adds the web host's hosted service after any hosted services you registered; - it builds the `IServiceProvider` from `builder.Services`; - it calls `MakeReadOnly()` on the service collection, so a later `builder.Services.AddScoped<...>()` throws `InvalidOperationException` ("The service collection cannot be modified because it is read-only."); - it returns a `WebApplication`. A second `Build()` call throws `InvalidOperationException` ("Build can only be called once."). `WebApplication` implements `IHost`, `IApplicationBuilder` and `IEndpointRouteBuilder`, which is why the same `app` variable takes `app.UseHttpsRedirection()`, `app.MapGet(...)` and `app.Run()`. It also exposes `app.Services`, `app.Configuration`, `app.Environment`, `app.Lifetime`, `app.Logger` and `app.Urls`. When the pipeline is assembled, `WebApplication` adds a few pieces itself — the developer exception page in Development, routing when endpoints exist, and endpoint execution at the end — so a template's `Program.cs` never calls `UseEndpoints`. ## What Run does `app.Run()` calls the host's run loop: it starts hosted services and the web host, which builds the request pipeline and lets Kestrel bind its addresses, then **blocks the calling thread** until the application stops (Ctrl+C, SIGTERM, or `app.Lifetime.StopApplication()`), and finally disposes the host. | Method | Returns | Behaviour | |---|---|---| | `app.Run(url?)` | `void` | Starts and blocks until shutdown | | `app.RunAsync(url?)` | `Task` | Same, completing when the app shuts down | | `app.StartAsync()` | `Task` | Starts and returns once the server is ready | | `app.StopAsync()` | `Task` | Stops a started app | Anything written after `app.Run();` executes only after shutdown. ## A common mistake Registering a service after `Build()` — for example in a block that runs only in Development and sits below `var app = builder.Build();` — throws at startup because the collection is sealed. All registrations belong above `Build()`; environment checks there use `builder.Environment.IsDevelopment()`. ## What CreateBuilder does not do for you The defaults stop at infrastructure. `CreateBuilder` registers no application frameworks and adds no request-handling policy: - no controllers, Razor Pages or OpenAPI — `AddControllers()`, `AddRazorPages()` and `AddOpenApi()` are explicit calls; - no HTTPS redirection, HSTS, exception handler or CORS — each is an explicit `app.Use...` call after `Build()`; - no authentication scheme — `WebApplication` inserts the authentication and authorization middleware only once their services are registered. That split is the useful mental model in an interview: **`CreateBuilder` decides how the process is hosted; your code decides what the application does.** Reading a `Program.cs` top to bottom, everything above `Build()` should answer "what services and settings exist?" and everything below it "what happens to a request, in what order?". A file that mixes the two — resolving services from `app.Services` in the middle of registrations, or registering after `Build()` — is the first thing a reviewer flags.

  • What happens if code calls builder.Services.AddSingleton<...>() after builder.Build() in ASP.NET Core 10?
    It throws `InvalidOperationException` with "The service collection cannot be modified because it is read-only." `Build()` creates the provider from the collection and then calls `MakeReadOnly()`, so every registration has to happen before it.
  • Why can WebApplicationBuilder read builder.Configuration values before Build() is called?
    `builder.Configuration` is a `ConfigurationManager`, which is both a configuration builder and a live `IConfiguration`. Sources added by `CreateBuilder` are already loaded, so `GetConnectionString` or `GetSection` work immediately, which is what the old `Startup` constructor's injected `IConfiguration` was used for.
  • When would you call app.RunAsync() instead of app.Run()?
    When `Program.cs` is already asynchronous or the caller must not block a thread — `RunAsync()` returns a `Task` that completes at shutdown. `StartAsync()` goes further, returning as soon as the server is listening, which suits code that must keep working after startup.

Like a restaurant before opening: the builder phase stocks the kitchen and hires staff, Build locks the staff list and opens the dining room layout for arranging, and Run unlocks the front door and keeps the place open until closing time.

  • builder.Build() starts Kestrel and begins accepting requests
  • Services can still be registered on builder.Services after Build
  • app.Run() returns as soon as the server is listening
  • Configuration cannot be read until after builder.Build()
  • CreateBuilder gives an empty host; you must add Kestrel and logging yourself
open as a page

In ASP.NET Core 10, what do app.Urls and the url argument of app.Run(url) or app.RunAsync(url) do, and how do they interact with configured URLs?

level: middleimportance: should knowfreq 35%

basics

~20 s

app.Urls is the server's address list, writable until the server starts; the url argument of Run or RunAsync clears it and adds that one URL. Configured URLs such as ASPNETCORE_URLS are read only when the list is still empty at start.

open as a page

In ASP.NET Core 10, why does builder.Host.UseEnvironment("Staging") throw after WebApplication.CreateBuilder, and how does WebApplicationOptions solve it?

level: middleimportance: should knowfreq 38%

basics

~10 s

CreateBuilder fixes the environment, content root, web root and application name while it is constructed, so builder.Host or builder.WebHost changing them throws NotSupportedException. Pass them up front in WebApplicationOptions to CreateBuilder instead.

open as a page

How would you move a 2019 ASP.NET Core veterinary-clinic API built on Startup.cs and WebHost.CreateDefaultBuilder onto WebApplicationBuilder in .NET 10?

level: seniorimportance: should knowfreq 48%

basics

~10 s

Replace WebHost.CreateDefaultBuilder with WebApplication.CreateBuilder, move ConfigureServices into builder.Services and Configure below builder.Build(), swap IHostingEnvironment for app.Environment and UseMvc for MapControllers; builder.WebHost.UseStartup is not supported.

open as a page

When would you use WebApplication.CreateEmptyBuilder instead of CreateBuilder in ASP.NET Core 10, and what must you add back yourself?

level: middleimportance: nice to knowfreq 16%

basics

~20 s

CreateEmptyBuilder builds a WebApplicationBuilder with no defaults: no server, no appsettings or environment-variable configuration, no logging providers and no routing services. Use it for the smallest, fully explicit hosts, adding UseKestrelCore, AddRoutingCore and anything else yourself.

open as a page