Background tasks with hosted services
Some work should not happen inside a web request: sending emails, cleaning old data or processing uploads. This lesson builds a BackgroundService, shows how to use scoped services such as a DbContext inside it, and adds a queue so actions can hand off work.
- StartAction saves the orderResponds to the user at once
- Step 2Channel.WriterQueues the order id
- Step 3BackgroundServiceReads the next id
- Step 4New scopeFresh DbContext and services
- EndReceipt sentErrors logged; the loop continues
Hosted services
A hosted service starts with the app and runs alongside it. BackgroundService is the base class: you override ExecuteAsync and loop until the stoppingToken is cancelled when the app shuts down.
Hosted services are singletons. A DbContext is scoped, so you must create a scope for each unit of work instead of injecting the context directly.
A scheduled cleanup job
public class CleanupService(IServiceScopeFactory scopes, ILogger<CleanupService> log) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromHours(1));
while (await timer.WaitForNextTickAsync(stoppingToken))
{
try
{
await using var scope = scopes.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<ShopContext>();
var cutoff = DateTime.UtcNow.AddDays(-30);
var removed = await db.Carts.Where(c => c.UpdatedAt < cutoff).ExecuteDeleteAsync(stoppingToken);
log.LogInformation("Removed {Count} old carts", removed);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
log.LogError(ex, "Cleanup failed"); // keep the loop alive
}
}
}
}
builder.Services.AddHostedService<CleanupService>();A queue for work from requests
An action puts a job in a Channel and returns at once; the background service processes jobs one by one.
builder.Services.AddSingleton(Channel.CreateBounded<int>(100)); // order ids
builder.Services.AddHostedService<ReceiptSender>();
// In the controller after saving an order:
await channel.Writer.WriteAsync(order.Id, ct);
public class ReceiptSender(Channel<int> channel, IServiceScopeFactory scopes) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var orderId in channel.Reader.ReadAllAsync(stoppingToken))
{
await using var scope = scopes.CreateAsyncScope();
await scope.ServiceProvider.GetRequiredService<IReceiptService>().SendAsync(orderId, stoppingToken);
}
}
}Know the limits
- In-memory queues are lost when the app restarts; for important work, store jobs in the database or use a queue service.
- With several app instances, each runs its own copy of a scheduled job; use a lock or a dedicated worker.
- Catch exceptions inside the loop; an unhandled one stops the service (and by default the host).
- Hosting platforms may stop idle apps; turn on Always On or use a separate worker process for critical jobs.
Interview question
How do you use a DbContext inside a BackgroundService?
A hosted service is a singleton, while DbContext is registered as scoped, so injecting it directly is wrong and fails scope validation. Inject IServiceScopeFactory, create a scope with CreateAsyncScope for each unit of work, resolve the DbContext from scope.ServiceProvider, and dispose the scope when done. IDbContextFactory is another option.
Want the full details? Read the official Microsoft documentation for this topic.