.NET › Background Services
What is the significance of the order of AddHostedService registrations relative to StartAsync execution, and can you control it?
IntermediateAnswer
By default, IHostedService.StartAsync is called for each registered hosted service in registration order, sequentially, before the host considers startup complete -- if one StartAsync throws, subsequent services won't start and the host fails to launch. Since .NET's default behavior runs StartAsync calls sequentially (not concurrently) but BackgroundService's own ExecuteAsync loop runs concurrently once started, you generally shouldn't rely on strict ordering for long-running work, but initial startup sequencing is deterministic based on registration order.
// Order matters for StartAsync sequencing:
builder.Services.AddHostedService<DatabaseMigrationService>(); // runs first, must complete
builder.Services.AddHostedService<CacheWarmupService>(); // runs second, after migration's StartAsync returnsReal-world example A team ensures database migrations complete before any other background service starts by registering a DatabaseMigrationService first, relying on the Generic Host's sequential StartAsync ordering to enforce this dependency.