🎬 Lifecycle Hooks
Run code on app start/stop. Warm cache, close connections cleanly.
public class StartupService : IHostedService
{
public async Task StartAsync(CancellationToken cancellationToken)
{
// Runs when app starts
await WarmCacheAsync();
await CheckDatabaseConnectionAsync();
}
public async Task StopAsync(CancellationToken cancellationToken)
{
// Runs when app stops (graceful shutdown)
await FlushLogsAsync();
await CloseConnectionsAsync();
}
}
// Register
services.AddHostedService();
Use Cases: Cache warming, health checks, cleanup tasks, connection pooling.
Execution Order: StartAsync runs before app accepts requests. StopAsync during graceful shutdown.
