Covers consuming scoped services from a singleton BackgroundService with IServiceScopeFactory.CreateAsyncScope per unit of work, including cancellation, per-item error handling, scope granularity and the .NET 8+ host behaviour on unhandled exceptions.
AddHostedService<T>() registers the worker as a singleton, so a scoped DbContext in its constructor would be a captive dependency: one context for the life of the process (Development throws at start-up). Instead, inject IServiceScopeFactory and create a scope per unit of work:
await using var scope = scopes.CreateAsyncScope();
var svc = scope.ServiceProvider.GetRequiredService<IOrderService>();
Each message or tick gets a fresh context that is disposed at the end. Pass stoppingToken everywhere, use PeriodicTimer for polling, and catch exceptions per item: since .NET 6 an unhandled exception in ExecuteAsync stops the host by default. If only a context is needed, IDbContextFactory<T> is simpler. Trade-off: smaller scopes mean fresher state and less memory, but more allocations per item.
"A hosted service is a singleton: the host resolves it once from the root provider at start-up. If I put
AppDbContextin its constructor, I get one context for the life of the process: not thread-safe, change tracker growing for ever, and stale data. In Development the container refuses with 'Cannot consume scoped service from singleton'; in Production it quietly works until it doesn't.So I inject
IServiceScopeFactory, which is a singleton, and create a scope for each unit of work. In a polling worker that's one scope per tick; in a queue consumer, one per message. Inside the scope I resolve the service I need, usually a single entry point likeIOrderProcessor, so the rest of the code is plain constructor injection. I useCreateAsyncScope()withawait usingso anything that's async-disposable is disposed correctly.Two more things matter in production. Cancellation: I pass
stoppingTokeninto every call and usePeriodicTimer, so shutdown is quick and doesn't hit the host's shutdown timeout. And errors: since .NET 6, an unhandled exception inExecuteAsyncstops the whole host by default. That's usually what you want for a bug, but one poisoned message shouldn't take the app down, so I catch per item, log with the item id, and move on or dead-letter it. The mistake I see is creating one scope outside the loop, which is exactly the captive dependency again with extra steps."
| Inject | Result |
|---|---|
AppDbContext |
Captive: one context for ever, Development start-up fails |
IServiceProvider |
Resolves from root: same problem, plus service locator |
IServiceScopeFactory |
Correct: scope per unit of work |
IDbContextFactory<AppDbContext> |
Correct when you only need a context |
| Granularity | When | Trade-off |
|---|---|---|
| Per message | Queue consumers | Isolation; failure affects one message |
| Per batch | Bulk processing (e.g. 500 rows) | Fewer allocations; one bad row can fail the batch |
| Per tick | Polling jobs | Simple; keep batches bounded |
| Whole loop | Never | Captive dependency |
An outbox publisher polled every [5 seconds] and published up to [200] messages per tick. Moving from a constructor-injected context to a scope per tick took memory from [steadily growing to 1.2 GB] to a flat [180 MB], and per-message try/catch meant one malformed payload no longer stopped the host, which had previously caused [two outages].
Checks that the candidate can write a correct BackgroundService that consumes scoped services, with the right scope granularity, cancellation and error handling.
Green flags
CreateAsyncScope() with await using, scope inside the loopstoppingToken, uses PeriodicTimerRed flags
DbContext directly or resolves it from IServiceProviderAddHostedService<T>() is TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, T>()). At start-up the host resolves IEnumerable<IHostedService> from the root provider and calls StartAsync on each in registration order.
Host.StartAsync
→ root.GetServices<IHostedService>() (singletons, root scope)
→ foreach: await service.StartAsync(ct)
BackgroundService.StartAsync → ExecuteTask = ExecuteAsync(stoppingToken)
(returns as soon as ExecuteAsync hits its first real await)
Because ExecuteAsync runs synchronously until its first incomplete await, heavy synchronous work at the top delays every later hosted service and the web server. Use await Task.Yield() or start with an awaited timer.
ExecuteAsync (singleton, root)
loop:
┌─ await using scope = scopeFactory.CreateAsyncScope()
│ processor = scope.GetRequiredService<IOrderProcessor>() (scoped)
│ └─ AppDbContext (scoped, new)
│ await processor.ProcessAsync(item, ct)
└─ scope disposed → context disposed, connection back to pool
Resolve one top-level service from the scope, then let constructor injection do the rest. That keeps the service-locator call confined to the worker.
HostOptions.BackgroundServiceExceptionBehavior defaults to StopHost: an unhandled exception is logged and the host stops (process exits; your orchestrator restarts it).Ignore restores old behaviour: the worker silently dies while the app keeps running, which is worse.HostOptions.ServicesStartConcurrently / ServicesStopConcurrently and IHostedLifecycleService for finer start-up hooks.stoppingToken is signalled when StopAsync is called. The host waits HostOptions.ShutdownTimeout (30 seconds by default in .NET 8+) for ExecuteAsync to finish. If you ignore the token, Kubernetes' SIGTERM grace period may kill the pod mid-write.
Processing several messages in parallel? Each parallel branch needs its own scope. A single scope shared across Parallel.ForEachAsync branches shares a DbContext and throws.
AppDbContext into a BackgroundService constructor and run in Development; read the exception.ExecuteAsync without a try/catch and watch the host stop; then set BackgroundServiceExceptionBehavior.Ignore and notice the silent failure.docker stop) while processing and confirm the worker stops within the shutdown timeout.A polling worker that processes pending orders with a scope per batch.
using Microsoft.EntityFrameworkCore;
namespace Orders.Worker;
public sealed class Order
{
public int Id { get; set; }
public string Status { get; set; } = "Pending";
public int Attempts { get; set; }
}
public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<Order> Orders => Set<Order>();
}
public interface IOrderProcessor
{
Task<int> ProcessPendingAsync(int batchSize, CancellationToken ct);
}
// Scoped: plain constructor injection, no knowledge of scopes.
public sealed class OrderProcessor(AppDbContext db, ILogger<OrderProcessor> logger) : IOrderProcessor
{
private const int MaxAttempts = 5;
public async Task<int> ProcessPendingAsync(int batchSize, CancellationToken ct)
{
var pending = await db.Orders.Where(o => o.Status == "Pending")
.OrderBy(o => o.Id).Take(batchSize).ToListAsync(ct);
var done = 0;
foreach (var order in pending)
{
try
{
await FulfilAsync(order, ct); // must be idempotent: a crash before SaveChanges means a retry
order.Status = "Processed";
done++;
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// One bad order must not stop the batch or the host.
order.Attempts++;
if (order.Attempts >= MaxAttempts) order.Status = "DeadLettered";
logger.LogError(ex, "Order {OrderId} failed (attempt {Attempt})", order.Id, order.Attempts);
}
}
await db.SaveChangesAsync(ct); // one transaction per batch/scope
return done;
}
private static Task FulfilAsync(Order order, CancellationToken ct) => Task.CompletedTask;
}
// Singleton: only singleton dependencies in the constructor.
public sealed class OrderWorker(IServiceScopeFactory scopes, ILogger<OrderWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(5));
while (await timer.WaitForNextTickAsync(stoppingToken))
{
try
{
await using var scope = scopes.CreateAsyncScope(); // fresh DbContext per tick
var processor = scope.ServiceProvider.GetRequiredService<IOrderProcessor>();
var count = await processor.ProcessPendingAsync(200, stoppingToken);
if (count > 0) logger.LogInformation("Processed {Count} orders", count);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break; // normal shutdown
}
catch (Exception ex)
{
// Transient DB failure: log and try again next tick instead of stopping the host.
logger.LogError(ex, "Order batch failed");
}
}
}
}
using Microsoft.EntityFrameworkCore;
using Orders.Worker;
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddDbContext<AppDbContext>(o =>
o.UseSqlServer(builder.Configuration.GetConnectionString("Orders")));
builder.Services.AddScoped<IOrderProcessor, OrderProcessor>();
builder.Services.AddHostedService<OrderWorker>();
builder.Services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(20));
builder.Build().Run();
AppDbContext or a repository into the worker's constructor. Why it is wrong: The worker is a singleton; the context becomes captive for the process lifetime. Instead: IServiceScopeFactory and a scope per unit of work.while loop. Why it is wrong: It lives as long as the worker, so it is still a captive context with a growing change tracker. Instead: Create the scope inside the loop.IServiceProvider and calling GetRequiredService<AppDbContext>(). Why it is wrong: That resolves from the root provider; Development throws, Production leaks. Instead: CreateAsyncScope() first.ExecuteAsync. Why it is wrong: Since .NET 6 one unhandled exception stops the host. Instead: Catch per item or per batch, log with context, and keep going (or dead-letter).OperationCanceledException from the stopping token as an error. Why it is wrong: It is normal shutdown and pollutes logs and alerts. Instead: Filter with when (stoppingToken.IsCancellationRequested) and exit.await in ExecuteAsync. Why it is wrong: It blocks host start-up, delaying Kestrel and other hosted services. Instead: Start with an awaited timer or await Task.Yield().DbContext and EF throws on concurrent use. Instead: One scope per branch.The worker should be a thin host for units of work: its only job is orchestration (timer, scope, cancellation, top-level error handling). It creates a scope, resolves one entry point such as IOrderProcessor, runs it and disposes. Everything that decides what happens to an order (validation, state changes, retries, dead-lettering) lives in scoped services that are unit-testable without the hosting machinery. That keeps the IServiceScopeFactory call in one place, which is the acceptable face of the service locator: infrastructure code at the composition boundary.
The scope is also your transaction boundary: one SaveChangesAsync per scope. Anything shared across scopes (an IMemoryCache, a rate limiter) must be a thread-safe singleton, and because a crash can happen after side effects but before the commit, processing must be idempotent (idempotency keys, status checks, or the outbox pattern).
| Approach | When it fits | Cost | When not to |
|---|---|---|---|
IServiceScopeFactory per unit of work |
Worker needs several scoped services | One scope allocation per unit | One dependency only |
IDbContextFactory<T> |
Worker only needs a context | You manage context disposal | You need scoped domain services too |
| A queue library's own scoping (MassTransit, Azure Functions, Wolverine) | Message consumers with retries and dead-letter queues built in | Framework coupling | Simple polling jobs |
| Hangfire / Quartz jobs | Scheduled jobs with retries and dashboards | Extra infrastructure | Trivial periodic work |
I measure a worker by throughput per tick, queue lag, dead-letter count and memory trend; a flat working set across a day is the sign the scoping is right.
In ASP.NET Core, register AddProblemDetails(), one or more IExceptionHandler implementations (.NET 8+) with AddExceptionHandler<T>(), and app.UseExceptionHandler() early in the pipeline. Handlers log once and map known exceptions to the right status code and an RFC 9457 ProblemDetails body, and never leak stack traces in production. For the process as a whole, AppDomain.CurrentDomain.UnhandledException is a last-chance notification: you can log and flush, but the process still terminates. TaskScheduler.UnobservedTaskException fires when a faulted task that nobody awaited is garbage-collected; it does not crash the process by default. In a BackgroundService, an unhandled exception in ExecuteAsync stops the host by default (.NET 6+). async void exceptions go to the synchronisation context and usually crash the process, so avoid async void except for event handlers.
It is a captive dependency. The singleton was built once, from the first request's scope, so it holds that request's DbContext for ever. Every user now shares one context: its identity map returns stale entities that were tracked earlier, concurrent requests hit it at the same time and EF throws "A second operation was started", and the change tracker grows. Often the first scope's disposal even leaves it disposed (ObjectDisposedException).
Development would have thrown, because ValidateScopes is on only in Development by default. I confirm by enabling ValidateScopes and ValidateOnBuild and reading the exception. The fix is to make PricingService scoped, or, if it truly must be a singleton (it holds a cache), inject IDbContextFactory<AppDbContext> and create a context per operation. Then turn validation on everywhere.
When the container can't build something up front, inject a factory instead of the object.
AddScoped<IFoo>(sp => ...)) runs logic at resolution time, for example choosing an implementation from configuration.Func<T> or Lazy<T>; you register them explicitly.ActivatorUtilities.CreateFactory (the generic ObjectFactory<T> overload arrived in .NET 8), which mixes your argument with container services and caches the reflection.The key rule: anything a factory creates is owned by the caller, who must dispose it. The trade-off is flexibility against hidden lifetimes: factories are the main way captive and leaked dependencies sneak in.
How to tell it (STAR)
**S:** At [company], our order API [went down twice in a month], and its memory climbed to over a gigabyte between deploys. **T:** I [owned the outbox publisher] and needed to make it stable. **A:** A gcdump showed one DbContext tracking hundreds of thousands of outbox rows: the worker was a singleton with the context injected in its constructor, and scope validation was off because every environment ran as Production. The outages came from one bad message throwing out of ExecuteAsync, which stops the host since .NET 6. I rewrote it to create a scope per tick, bounded the batch, caught failures per message with a retry count and dead-letter, and turned scope validation on everywhere. **R:** Memory went flat at [about 180 MB], outbox lag stayed under [10 seconds], and we've had [no] worker-caused outages since.
Last updated 23 Nov 2026.