.NET › Generic Host

What is the role of IHostLifetime, and how does it differ across console applications, Windows Services, and containers?

Intermediate

Answer

IHostLifetime is the abstraction responsible for actually starting and stopping the host in a way appropriate to its hosting environment -- ConsoleLifetime (default) listens for Ctrl+C/SIGTERM signals directly, WindowsServiceLifetime integrates with the Windows Service Control Manager's start/stop commands, and SystemdLifetime integrates with systemd's service notification protocol -- letting the same application code run correctly whether launched interactively, as an installed OS service, or inside a container, with the host automatically selecting the appropriate implementation via UseWindowsService()/UseSystemd() or defaulting to ConsoleLifetime.
// Default: ConsoleLifetime, handles Ctrl+C and SIGTERM directly
var host = Host.CreateApplicationBuilder(args).Build();

// Explicit: WindowsServiceLifetime, integrates with Windows SCM
builder.Services.AddWindowsService();  // swaps in WindowsServiceLifetime when actually running as a service
Real-world example A single Worker Service codebase runs identically in a developer's console during debugging (ConsoleLifetime) and as a production Windows Service (WindowsServiceLifetime), with the host automatically selecting the correct lifetime implementation for each context.

Common follow-ups: How would you write a custom IHostLifetime for an unsupported hosting scenario?;What happens if UseWindowsService() is called but the app isn't actually running as a Windows Service?