⚙️ Asp.Net Core: Fix a Hosted Service Starting Before Its Dependency
IHostedService instances registered via AddHostedService<T>() have their StartAsync called in registration order, but that only guarantees the method call happens in order — if a service kicks off fire-and-forget async work inside its own StartAsync without awaiting it, the method returns before that work (warming a cache, establishing a connection) is actually done, so the next hosted service starts believing the dependency is ready when it genuinely isn’t.
🔎 The Problem
public class CacheWarmupService : IHostedService
{
public Task StartAsync(CancellationToken ct)
{
_ = WarmCacheAsync(ct); // fire-and-forget, never awaited
return Task.CompletedTask; // returns immediately, cache still empty
}
}
// next registered hosted service assumes the cache is already warm
✅ Fix: Await Real Initialization, or Signal Readiness Explicitly
- Make a hosted service’s own initialization work genuinely awaited inside
StartAsyncbefore it returns, rather than starting background work and returning immediately — the host only guarantees startup order, not that a fire-and-forget task inside a previous service has finished. - If one hosted service truly needs another’s state, expose that state through a shared singleton with its own readiness signal that the dependent service awaits explicitly, instead of relying on registration order as an implicit contract.
- Add a startup-time log line marking when each service’s real initialization work completes, not just when
StartAsyncreturns, so a wrong ordering assumption shows up in logs instead of as an intermittent runtime failure.
🚨 Why This Is Dangerous
- A hosted service that “usually” works because its dependency happens to finish fast enough in most environments can fail unpredictably under load or on a slower machine — exactly the kind of bug that doesn’t reproduce in a quick local test.
The host guarantees the order your services start in — it never promised any of them would be finished by the time the next one begins.




