The .NET Generic Host and WebApplicationBuilder: default configuration sources, logging providers and DI registrations created by CreateBuilder, what Build() and Run() do, IHostedService start order, IHostApplicationLifetime events and how graceful shutdown works with HostOptions.ShutdownTimeout.
The Generic Host (IHost) is the common runtime shell for every modern .NET app, web or worker: it owns configuration, logging, dependency injection and the application lifetime. WebApplication.CreateBuilder(args) creates one with sensible defaults: appsettings.json, appsettings.{Environment}.json, user secrets in Development, environment variables and command-line args; console, debug and EventSource logging; and Kestrel. Build() freezes the service collection and builds the IServiceProvider. Run() starts hosted services, then the web server, and blocks until shutdown. On SIGTERM or Ctrl+C the host fires ApplicationStopping, stops accepting requests, lets in-flight ones finish, stops hosted services and exits within HostOptions.ShutdownTimeout (30 seconds by default). The trade-off: the defaults are great, but you must understand them to override them deliberately.
"The Generic Host is the shell every modern .NET app runs in. It came from ASP.NET Core and was generalised in .NET Core 3.0 so web apps, worker services and console tools all share the same configuration system, logging, DI container and lifetime.
WebApplicationBuilder, from .NET 6, is a thin, simpler front end over it.When I call
WebApplication.CreateBuilder(args), it loads configuration in a fixed order:appsettings.json,appsettings.{Environment}.json, user secrets when the environment is Development, environment variables, then command-line arguments, with later sources winning. It registers the console, debug and EventSource logging providers, the options system, Kestrel and the IIS integration. I then add my services tobuilder.Services.Build()creates theIServiceProvider, and from that point the service collection is read-only.Run()callsStartAsyncon everyIHostedServicein registration order, starts the server, raisesApplicationStartedand waits. When the platform sends SIGTERM, the host raisesApplicationStopping, the server stops accepting connections and drains in-flight requests, hosted services are stopped in reverse order, and the process exits, all withinHostOptions.ShutdownTimeout, 30 seconds by default since .NET 8.The mistake I see is people doing heavy work in a hosted service's
StartAsync, which blocks the server from starting, or ignoring the shutdown token so deployments kill work mid-flight. The host gives you an orderly start and an orderly stop; your job is to honour both."
CreateBuilder gives you| Area | Defaults |
|---|---|
| Configuration | appsettings.json → appsettings.{Env}.json → user secrets (Development only) → environment variables → command line |
| Environment | ASPNETCORE_ENVIRONMENT or DOTNET_ENVIRONMENT, default Production |
| Logging | Console, Debug, EventSource, EventLog (Windows); filtered by the Logging section |
| DI | Built-in container; ValidateScopes and ValidateOnBuild on in Development |
| Server | Kestrel, IIS integration |
| Web root / content root | wwwroot, current directory |
| Event | When | Use it for |
|---|---|---|
ApplicationStarted |
Server listening, all hosted services started | Warm-up signal, readiness |
ApplicationStopping |
Shutdown requested | Stop accepting new work, flip readiness to unhealthy |
ApplicationStopped |
Shutdown complete | Final flush of telemetry |
In an API on Azure Container Apps, the platform sends SIGTERM and waits 30 seconds by default before SIGKILL. With a default host and no custom shutdown code, in-flight requests finished cleanly; the one queue consumer that ignored its stoppingToken was the only thing that lost messages, until it was changed to stop pulling new messages when the token fired.
Checks whether the candidate understands what the template does for them and how the app starts and stops.
Green flags
Build() freezes DI and what Run() starts.ApplicationStopping, draining and ShutdownTimeout.StartAsync.Red flags
WebApplicationBuilder is unrelated to the Generic Host.Before the Generic Host, ASP.NET Core had WebHost and console apps had nothing, so every worker re-invented configuration, logging and shutdown. IHost gives a single model:
IHost
├── IConfiguration (layered providers)
├── ILoggerFactory (providers + filters)
├── IServiceProvider (DI container)
├── IHostEnvironment (EnvironmentName, ContentRootPath)
├── IHostApplicationLifetime
└── IHostedService[] (the web server is started by GenericWebHostService, itself a hosted service)
builder.Build():
ServiceProvider from builder.Services. In Development, ValidateOnBuild tries to construct every registration once to find missing dependencies, and ValidateScopes catches scoped services captured by singletons.WebApplication, which is both the IHost and the IApplicationBuilder/IEndpointRouteBuilder you add middleware and endpoints to.After this, builder.Services is read-only; adding a service throws InvalidOperationException.
app.Run() → StartAsync:
IHostedLifecycleService.StartingAsync (.NET 8+).IHostedService.StartAsync, sequentially in registration order (set HostOptions.ServicesStartConcurrently = true to start them in parallel).GenericWebHostService builds the middleware pipeline and starts Kestrel; it is registered such that the server starts after services registered before it.ApplicationStarted fires.BackgroundService.StartAsync returns as soon as ExecuteAsync hits its first real await, so a synchronous loop at the top of ExecuteAsync blocks start-up.
SIGTERM / Ctrl+C / StopApplication()
│
▼
ApplicationStopping fires
│
▼
Server stops accepting connections, drains in-flight requests
│
▼
Hosted services StopAsync in REVERSE order (stoppingToken cancelled for BackgroundService)
│
▼
ApplicationStopped fires ─► DI container disposed ─► process exits
All of this must complete inside HostOptions.ShutdownTimeout (5 s before .NET 8, 30 s from .NET 8). On Linux, ConsoleLifetime handles SIGTERM via PosixSignalRegistration. If the orchestrator's grace period (Kubernetes terminationGracePeriodSeconds, 30 s by default) is shorter than your timeout, the process is killed first.
Host.CreateApplicationBuilder (.NET 7+): the same builder style for worker services, without a web server.WebApplication.CreateSlimBuilder: fewer defaults, for Native AOT.WebApplication.CreateEmptyBuilder: nothing registered; you opt in to everything.IHostedServices that log in StartAsync/StopAsync; observe start order and reverse stop order.await Task.Delay(10_000) in a StartAsync and measure how long until the first request succeeds.HostOptions.ShutdownTimeout to 2 s and repeat; read the log when the timeout is exceeded.builder.Services.AddSingleton<Foo>() after Build() and read the exception.Hooking into the host lifetime and setting the shutdown timeout explicitly.
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Give in-flight requests and background work time to finish; keep it below the orchestrator's grace period
builder.Services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(25));
builder.Services.AddSingleton<ReadinessState>();
builder.Services.AddHostedService<WarmUpService>();
var app = builder.Build(); // services are frozen from here
var lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();
var readiness = app.Services.GetRequiredService<ReadinessState>();
lifetime.ApplicationStarted.Register(() => app.Logger.LogInformation("Started in {Env}", app.Environment.EnvironmentName));
lifetime.ApplicationStopping.Register(() =>
{
readiness.IsReady = false; // load balancer stops sending new traffic
app.Logger.LogInformation("Stopping: draining requests");
});
app.MapGet("/health/ready", (ReadinessState r) => r.IsReady ? Results.Ok() : Results.StatusCode(503));
app.Run();
public sealed class ReadinessState { public volatile bool IsReady; }
// Warm-up runs in ExecuteAsync so it does not block the server from starting
public sealed class WarmUpService(ReadinessState readiness, ILogger<WarmUpService> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken); // e.g. prime caches
readiness.IsReady = true;
logger.LogInformation("Warm-up complete");
}
}
IHostedService.StartAsync. Why it is wrong: Hosted services start sequentially before the server, so the app does not listen until it finishes and health checks fail. Instead: Start work in BackgroundService.ExecuteAsync after an await, or use ApplicationStarted.Build(). Why it is wrong: The container is already built; it throws. Instead: Register everything on builder.Services.stoppingToken to every async call, catch OperationCanceledException at the loop boundary, and stop pulling new work when it fires.ShutdownTimeout longer than the orchestrator's grace period. Why it is wrong: Kubernetes sends SIGKILL after terminationGracePeriodSeconds, so the host never finishes. Instead: Keep the host timeout a few seconds below the platform's grace period.CreateBuilder only adds them when the environment is Development. Instead: Use Key Vault or environment variables elsewhere.builder.Configuration.Add... and expecting it to lose to environment variables. Why it is wrong: Sources added later win, so a JSON file added after the defaults overrides environment variables and command-line args. Instead: Insert sources deliberately and check the result with ((IConfigurationRoot)builder.Configuration).GetDebugView().StopAsync, and asserts it completes; also send SIGTERM to the container locally (docker stop).Environment.Exit to stop the app. Why it is wrong: It bypasses graceful shutdown and disposal. Instead: Call IHostApplicationLifetime.StopApplication().Seniors use the host's lifecycle rather than fighting it. The host already handles SIGTERM, draining and ordered disposal; what it cannot know is how long your work takes or what the load balancer is doing. So you align three numbers: the readiness probe period, HostOptions.ShutdownTimeout, and the orchestrator's grace period. You also know which builder to pick: CreateBuilder for most apps, CreateSlimBuilder for Native AOT where every default costs binary size.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
WebApplication.CreateBuilder |
Most web apps | A few defaults you may not use | Native AOT with tight size budgets |
WebApplication.CreateSlimBuilder |
Native AOT, minimal APIs | Opt in to HTTPS, Regex routing constraints and more | Apps needing the full defaults |
Host.CreateApplicationBuilder |
Worker services, queue consumers | No web server | Anything serving HTTP |
In ASP.NET Core, register AddProblemDetails(), one or more IExceptionHandler implementations (.NET 8+) with AddExceptionHandler<T>(), and app.UseExceptionHandler() early in the pipeline. Handlers log once and map known exceptions to the right status code and an RFC 9457 ProblemDetails body, and never leak stack traces in production. For the process as a whole, AppDomain.CurrentDomain.UnhandledException is a last-chance notification: you can log and flush, but the process still terminates. TaskScheduler.UnobservedTaskException fires when a faulted task that nobody awaited is garbage-collected; it does not crash the process by default. In a BackgroundService, an unhandled exception in ExecuteAsync stops the host by default (.NET 6+). async void exceptions go to the synchronisation context and usually crash the process, so avoid async void except for event handlers.
The ThreadPool is a process-wide set of reusable background threads that run queued work items: Task.Run, async continuations, timer callbacks and ASP.NET Core requests. Work goes into a global queue or, when queued from a pool thread, into that thread's local queue, and idle threads steal from others. The pool starts up to minimum threads (default: processor count) immediately on demand; above that it adds threads gradually, using a hill-climbing algorithm that measures throughput plus a starvation detector that injects threads when queued work is not progressing. That gradual injection is why blocking pool threads causes latency spikes.
Last updated 23 Nov 2026.