liveBook · Manning

AddHostedService

As explained in ASP.NET Core in Action, 3e

AddHostedService is a dependency-injection extension method that registers a hosted-service implementation.

AddHostedService<T>() registers a hosted-service implementation with ASP.NET Core dependency injection. Use it for long-running background work that starts with the application and continues until shutdown. section 34.1.1 section 34.4

Registering a background service

Register its dependencies first, then add the hosted service: builder.Services.AddHttpClient<ExchangeRatesClient>(); builder.Services.AddSingleton<ExchangeRatesCache>(); builder.Services.AddHostedService<ExchangeRatesHostedService>(); A BackgroundService typically overrides ExecuteAsync, repeats work until its CancellationToken signals shutdown, and can use IServiceProvider.CreateScope() when it needs scoped services. AddHostedService registers the implementation with a singleton lifetime. section 34.4

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains registration, singleton lifetime, cancellation, and scope creation, but defers advanced scheduling to Quartz.NET.
Examples
Uses an exchange-rate service that periodically calls a remote API and stores results in a shared cache.
What it assumes
Assumes familiarity with ASP.NET Core dependency injection and teaches hosted-service registration through a small background task.
What you can do after
Build it from scratch by registering a BackgroundService and running cancellable work during application lifetime.
How it connects
Connects hosted services with dependency injection, BackgroundService, IHostedService, cancellation tokens, and worker services.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.