Advertisement
Beginner .NET, Background Services

What is the difference between IHostedService and BackgroundService, and when would you implement IHostedService directly?

Short answer

IHostedService is the low-level interface with just StartAsync and StopAsync methods -- you implement it directly when you need precise control over startup/shutdown without an inherent long-running loop, such as a service that just registers something once and cleans up once.

Save .NET mock interview
Advertisement
AModel answer
IHostedService is the low-level interface with just StartAsync and StopAsync methods -- you implement it directly when you need precise control over startup/shutdown without an inherent long-running loop, such as a service that just registers something once and cleans up once. BackgroundService is a convenience base class implementing IHostedService specifically for the common case of a continuous work loop, handling the StartAsync/StopAsync plumbing for you so you only need to write ExecuteAsync.
// Direct IHostedService: no continuous loop, just start/stop hooks
public class MetricsRegistrationService : IHostedService {
    public Task StartAsync(CancellationToken ct) {
        MetricsRegistry.Register("my-service");
        return Task.CompletedTask;
    }
    public Task StopAsync(CancellationToken ct) {
        MetricsRegistry.Unregister("my-service");
        return Task.CompletedTask;
    }
}
Real-world example
A service that simply registers the application with a service discovery system at startup and deregisters at shutdown implements IHostedService directly, since it has no ongoing loop -- unlike a queue processor, which extends BackgroundService instead.
Likely follow-ups
  • Why does BackgroundService exist if IHostedService already covers this?
  • Can a class implement both patterns simultaneously?
Related topics