What is IHostedLifecycleService, and how does it provide more granular hooks than IHostedService's StartAsync/StopAsync?
Short answer
Introduced in .NET 8, IHostedLifecycleService adds StartingAsync, StartedAsync, StoppingAsync, and StoppedAsync hooks around the existing StartAsync/StopAsync, letting you run logic before and after each phase specifically -- useful for coordinating startup ordering between…
Advertisement
AModel answer
Introduced in .NET 8, IHostedLifecycleService adds StartingAsync, StartedAsync, StoppingAsync, and StoppedAsync hooks around the existing StartAsync/StopAsync, letting you run logic before and after each phase specifically -- useful for coordinating startup ordering between multiple hosted services or running cleanup logic guaranteed to execute after all StopAsync calls have completed.
public class MyLifecycleService : IHostedLifecycleService {
public Task StartingAsync(CancellationToken ct) { /* before StartAsync */ return Task.CompletedTask; }
public Task StartAsync(CancellationToken ct) { /* main start logic */ return Task.CompletedTask; }
public Task StartedAsync(CancellationToken ct) { /* after all StartAsync calls */ return Task.CompletedTask; }
// ... StoppingAsync, StopAsync, StoppedAsync similarly
}Real-world example
A service mesh sidecar registration hook uses StartedAsync to confirm the application is fully ready and register itself with a service discovery system only after every other hosted service has successfully started, avoiding a race condition.
Likely follow-ups
- Why was this added instead of relying purely on StartAsync/StopAsync ordering?
- How does this interact with multiple hosted services registered in the same app?
Related topics