ASP.NET Core › Background Tasks & Hosted Services

How does IHostApplicationLifetime let a BackgroundService react to application startup and shutdown events?

Intermediate

Answer

IHostApplicationLifetime exposes ApplicationStarted, ApplicationStopping, and ApplicationStopped CancellationTokens/events you can register callbacks against, letting a service run logic precisely when the application has fully started (useful for deferring work until all other services are ready) or precisely when shutdown begins (for final cleanup logic distinct from the service's own StopAsync).
public class MyService(IHostApplicationLifetime lifetime) : BackgroundService {
    protected override Task ExecuteAsync(CancellationToken stoppingToken) {
        lifetime.ApplicationStarted.Register(() => _logger.LogInformation("App fully started"));
        lifetime.ApplicationStopping.Register(() => _logger.LogInformation("App stopping..."));
        return Task.CompletedTask;
    }
}
Real-world example A service registration hook waits for ApplicationStarted before announcing itself to a service discovery system, ensuring it only advertises availability once the entire application (including all other hosted services) has successfully completed startup.

Common follow-ups: How does ApplicationStopping differ from the CancellationToken passed to ExecuteAsync?;What happens if a callback registered on ApplicationStopping throws an exception?