In ASP.NET Core, what is the difference between implementing IHostedService directly and deriving from BackgroundService, and how is either one registered?
answer
- two start/stop methods vs one loop
- StartAsync blocks the next service
- ExecuteAsync(CancellationToken stoppingToken)
- AddHostedService<T>() registers a singleton
- TryAddEnumerable: second call ignored
basics
~10 sIHostedService gives you StartAsync and StopAsync and nothing else; BackgroundService implements both and asks only for ExecuteAsync(stoppingToken), the long-running loop. Either is registered with builder.Services.AddHostedService<T>(), which adds a singleton.
solid answer
~40 s`IHostedService` is the raw contract: the host calls `StartAsync` when the app starts and `StopAsync` when it shuts down, and you own every thread, timer and cancellation in between. `BackgroundService` is an abstract base class that implements both for you: its `StartAsync` starts your `ExecuteAsync(CancellationToken stoppingToken)` as a task and returns at once, and its `StopAsync` cancels `stoppingToken` and waits for that task. So a loop goes in a `BackgroundService`, while short start-up or shut-down work fits a plain `IHostedService`. Both are registered with `builder.Services.AddHostedService<T>()`, which adds the type as a **singleton** `IHostedService`. Calling it twice for the same type still registers one instance.
code
csharp · 17 linespublic sealed class MeterSyncService(ILogger<MeterSyncService> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
logger.LogInformation("Pulling meter readings");
await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
}
}
}
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHostedService<MeterSyncService>();
var app = builder.Build();
app.Run();go deeper
Recall the two shapes: IHostedService with StartAsync and StopAsync, BackgroundService with one ExecuteAsync loop, and AddHostedService<T>() to register either.
Explain what BackgroundService's StartAsync and StopAsync do for you, why the instance is a singleton, and why the host's sequential start makes StartAsync the wrong place for a loop.
Show the consequences in production: registration order against the web server, duplicate registrations collapsing, and that every process registering the service runs its own copy.
Frame when in-process hosted services are the right home for background work at all, versus a separate worker deployment or a durable scheduler that survives restarts.
## Two contracts for work that lives as long as the app An ASP.NET Core app runs on the .NET Generic Host. Besides the web server, the host can run **hosted services**: objects it starts when the app starts and stops when the app shuts down. They are the framework's built-in place for work that is not tied to one HTTP request: a loop that polls meter readings, a cache warm-up, a consumer that reads a queue. There are two ways to write one: | | `IHostedService` | `BackgroundService` | |---|---|---| | Kind | interface in `Microsoft.Extensions.Hosting` | abstract class implementing `IHostedService` and `IDisposable` | | You write | `StartAsync(CancellationToken)` and `StopAsync(CancellationToken)` | `ExecuteAsync(CancellationToken stoppingToken)` | | Start-up | the host awaits your `StartAsync` before starting the next service | `StartAsync` starts `ExecuteAsync` as a task and returns a completed task | | Shut-down | you stop your own timers or tasks | `StopAsync` cancels `stoppingToken`, then waits for `ExecuteAsync` | | Fits | short start and stop work, or a timer you manage yourself | a loop that runs for the life of the app | ## What BackgroundService does for you `BackgroundService` is small, and knowing its body is what interviewers check: - `StartAsync` creates a `CancellationTokenSource` linked to the start-up token and, in .NET 10, runs **all** of `ExecuteAsync` through `Task.Run`, storing the task in the public `ExecuteTask` property. - It returns `Task.CompletedTask` at once, so a never-ending loop does not hold up start-up. - `StopAsync` cancels the token your loop received as `stoppingToken` and then waits for `ExecuteTask` to finish, bounded by the host's shutdown token. - `Dispose` cancels the same token source. - The host watches `ExecuteTask`: if it faults, the host logs the exception and, by default, stops the application. Only `ExecuteAsync` is abstract; `StartAsync`, `StopAsync` and `Dispose` are virtual, so you override them only to add behaviour, and you call the base implementation when you do. ## Registering: AddHostedService `AddHostedService<THostedService>()` (namespace `Microsoft.Extensions.DependencyInjection`) adds a `ServiceDescriptor.Singleton<IHostedService, THostedService>` through `TryAddEnumerable`. Three consequences follow: 1. **One instance per process.** A hosted service is a singleton, so it cannot take a scoped service such as a `DbContext` in its constructor; it creates a scope per unit of work instead. 2. **Duplicate calls collapse.** `TryAddEnumerable` skips a second registration of the same implementation type, so calling `AddHostedService<MeterSyncService>()` twice still runs one loop. 3. **Order matters.** The host resolves `IEnumerable<IHostedService>` and starts the services in registration order, one after another by default. `WebApplicationBuilder.Build()` appends the web server's own hosted service after yours, so your `StartAsync` methods finish before Kestrel starts listening. An overload takes a factory, `AddHostedService<T>(Func<IServiceProvider, T>)`, for a service that needs construction logic. ## Choosing between them - Pick **`BackgroundService`** for anything that loops: polling, draining a queue, a periodic sweep. You write one method and get cancellation and shutdown waiting for free. - Pick **plain `IHostedService`** when the work is a step at start or stop: warm a cache before the server listens, flush a buffer at shutdown. Because the host awaits `StartAsync`, a long-running loop placed there would keep every later service, and the server itself, from starting. - Hosted services start when the host starts, not on the first request, and they run in every process that registers them. ## Traps interviewers probe - **Overriding `StartAsync` without calling `base.StartAsync`.** `ExecuteAsync` is then never started, `ExecuteTask` stays `null`, and the host has nothing to watch; the service silently does nothing. - **Overriding `StopAsync` without calling `base.StopAsync`.** The loop is never told to stop, so shutdown waits for the timeout. - **Injecting the hosted service elsewhere.** `AddHostedService<T>()` registers it only as `IHostedService`, so asking the container for `T` fails. Register `T` as a singleton and forward it with the factory overload, `AddHostedService(sp => sp.GetRequiredService<T>())`, so the host and the consumers share one instance. - **Expecting one copy per deployment.** Each process that runs the app starts its own instance. ## A worked example In a water-utility billing app, a service that pulls meter readings from the field system every few minutes is a `BackgroundService`: a `while` loop in `ExecuteAsync` that awaits a delay with `stoppingToken`. A service that loads tariff tables into memory before the first bill is calculated is an `IHostedService` whose `StartAsync` does the load and whose `StopAsync` returns `Task.CompletedTask`.
- Why does a long loop placed in IHostedService.StartAsync delay the whole app?The host awaits each hosted service's `StartAsync` in turn, and by default (`HostOptions.ServicesStartConcurrently` is false) it starts them one at a time. In a `WebApplication` the web server's hosted service is registered after yours, so a `StartAsync` that never completes means Kestrel never starts listening. Long-running work belongs in `BackgroundService.ExecuteAsync`, which the base class starts as a task.
- Can a BackgroundService take a scoped service such as a DbContext in its constructor?No. `AddHostedService` registers it as a singleton, so a scoped dependency would be captured for the life of the app, and with scope validation on in Development the container refuses to resolve it. The service injects `IServiceScopeFactory` instead and creates a scope for each unit of work.
- AddHostedService registers the service as scoped, one instance per request
- Deriving from BackgroundService means overriding StartAsync and StopAsync
- A hosted service also needs AddSingleton<T>() or the host never starts it
- Put the endless loop in IHostedService.StartAsync so it starts early
- A hosted service starts lazily when the first HTTP request arrives