C# Reference ยท .NET, Tools and Concepts
The generic host
Reference for the .NET generic host: Host.CreateApplicationBuilder, hosted services, BackgroundService, startup and shutdown, and the app lifetime.
The generic host (IHost) is the object that owns a long-running .NET application: it builds the dependency injection container, loads configuration, sets up logging, and starts and stops hosted services. Worker services, web apps, and many tools are all built on it. ASP.NET Core's WebApplication is a host that also runs a web server.
You create one with Host.CreateApplicationBuilder(), register services on the builder, call Build(), and then Run() (blocks until shutdown) or StartAsync() / StopAsync() for finer control. Background work goes into an IHostedService, most conveniently by deriving from BackgroundService.
var builder = Host.CreateApplicationBuilder(args); builder.Services.AddHostedService<Worker>(); using IHost host = builder.Build(); await host.RunAsync();
Try it
This worker prints a few ticks, then asks the host to stop itself. The lifetime object lets any service request shutdown.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
IHostedService has two methods, StartAsync and StopAsync. Services start in registration order and stop in reverse order, which the next example shows.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
HostApplicationBuilder Host.CreateApplicationBuilder(string[]? args); IServiceCollection AddHostedService<THostedService>(this IServiceCollection services) where THostedService : class, IHostedService; public interface IHostedService { Task StartAsync(CancellationToken cancellationToken); Task StopAsync(CancellationToken cancellationToken); } public abstract class BackgroundService : IHostedService, IDisposable { protected abstract Task ExecuteAsync(CancellationToken stoppingToken); }
| Member | Description |
|---|---|
Host.CreateApplicationBuilder |
Preconfigured builder: configuration (appsettings, environment variables, arguments), logging, DI. |
host.RunAsync() |
Starts, then waits for Ctrl+C, SIGTERM or StopApplication, then stops. |
host.StartAsync() / StopAsync() |
Start and stop without blocking, useful in tests. |
IHostApplicationLifetime |
ApplicationStarted, ApplicationStopping, ApplicationStopped tokens and StopApplication(). |
IHostEnvironment |
EnvironmentName, ContentRootPath, IsDevelopment(). |
HostOptions |
ShutdownTimeout (default 30 seconds), BackgroundServiceExceptionBehavior. |
Errors: by default, an unhandled exception in ExecuteAsync stops the host (since .NET 6). The host logs the exception, so keep logging enabled in real apps.
Usage notes
ExecuteAsyncshould not block the start.BackgroundServicecalls it without awaiting the whole loop, but synchronous work before the firstawaitstill delays startup of later services. Start withawait Task.Yield()if you must do heavy setup.- Observe the stopping token. Pass it to every delay and I/O call so shutdown is quick. If a service ignores it, the host waits until
ShutdownTimeout. - Scoped services in a singleton worker. A hosted service lives for the whole app, so create a scope per unit of work:
using var scope = scopeFactory.CreateScope();and resolve scoped services (such as a database context) from it. - Periodic work:
PeriodicTimerinsideExecuteAsyncis simpler and safer than aSystem.Threading.Timer, because ticks never overlap. - Graceful shutdown.
Ctrl+CorSIGTERM(containers, systemd, Windows service stop) triggersStopAsyncin reverse order. Finish or persist in-flight work there. - Windows service and systemd:
AddWindowsService()andAddSystemd()adapt the host lifetime to those service managers. - Web apps are hosts. Everything here (hosted services, options, logging) also works in an ASP.NET Core app: ASP.NET Core overview.
- Testing: build the host with test services, then
StartAsyncandStopAsyncto check behavior without a process.