IHostedService is a .NET interface for components that start and stop with an application host. It provides lifecycle hooks for background work, such as processing queued emails or updating data periodically, without making a user wait for that work to finish. section 34.1
public interface IHostedService
{
Task StartAsync(CancellationToken cancellationToken);
Task StopAsync(CancellationToken cancellationToken);
}
The interface defines asynchronous start and stop methods, each receiving a cancellation token. section 34.1.1
For a long-running task, usually derive from BackgroundService instead of implementing the interface directly. Override ExecuteAsync and run the work until its cancellation token signals shutdown. Register the implementation with AddHostedService<T>(). section 34.1.1 section 34.4
Listing 34.3 Registering an IHostedService with the DI container
WebApplicationBuilder builder = WebApplication.CreateBuilder(args); builder.Services.AddHttpClient<ExchangeRatesClient>(); #1 builder.Services.AddSingleton<ExchangeRatesCache>(); #2 builder.Services.AddHostedService<ExchangeRatesHostedService>(); #3 #1 Registers the typed client as before #2 Adds the cache object as a singleton so it is shared throughout your app #3 Registers ExchangeRatesHostedService as an IHostedService
This registration adds the hosted service, its typed HTTP client, and a shared cache to dependency injection. section 34.1.1
StartAsync runs as part of application startup. Awaiting work there delays startup until it completes. That can be useful when initial data is essential, but continuous background work should not keep StartAsync waiting for the lifetime of the application. section 34.1.1
Refresh exchange rates in the background
A BackgroundService periodically fetches rates from a remote API and updates a shared cache. An endpoint reads from the cache instead of making its own remote call, keeping responses fast. If the app must have rates before it starts, StartAsync can wait for an initial successful update. section 34.1.1
Hosted service instances are singletons. To use a scoped dependency, such as an EF Core DbContext, create a scope with IServiceProvider.CreateScope(), resolve the dependency from that scope, and dispose the scope when the work is complete. Background work has no request scope automatically created for it. section 34.1.2
A hosted service can run inside an ASP.NET Core app or in a headless worker using the generic IHost. For more elaborate schedules, Quartz.NET typically runs its scheduler as a hosted service. section 34.2 section 34.3
