📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Your BackgroundService needs to read and update orders through the scoped AppDbContext and a scoped IOrderService. Show how you would write it correctly, explain why you can't inject them into the constructor, and cover cancellation, error handling and scope granularity.

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.

Mid-Level Coding Intermediate background-service dependency-injection ef-core hosted-services iservicescopefactory service-lifetimes

🎯 Key points

  • Hosted services are registered as singletons, so constructor-injected scoped services become captive: Development throws, other environments silently share one context (stale data, concurrency errors)
  • Inject IServiceScopeFactory; create a scope per unit of work with CreateAsyncScope and await using
  • Scope granularity: one per message, batch or tick, never one for the whole ExecuteAsync loop
  • Pass stoppingToken to every async call; PeriodicTimer.WaitForNextTickAsync for polling
  • Catch per item: since .NET 6 an unhandled exception stops the host (BackgroundServiceExceptionBehavior.StopHost); count attempts and dead-letter poison items
  • One SaveChangesAsync per scope is the transaction boundary; make processing idempotent because work can be retried
  • Alternatives: IDbContextFactory<T> when only a context is needed

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"A hosted service is a singleton: the host resolves it once from the root provider at start-up. If I put AppDbContext in 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 like IOrderProcessor, so the rest of the code is plain constructor injection. I use CreateAsyncScope() with await using so anything that's async-disposable is disposed correctly.

Two more things matter in production. Cancellation: I pass stoppingToken into every call and use PeriodicTimer, so shutdown is quick and doesn't hit the host's shutdown timeout. And errors: since .NET 6, an unhandled exception in ExecuteAsync stops 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."


Why not constructor injection

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

Scope granularity

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

Production example

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].

🔍 What the interviewer is checking

Checks that the candidate can write a correct BackgroundService that consumes scoped services, with the right scope granularity, cancellation and error handling.

Green flags

  • Explains hosted services are singletons and why constructor injection of scoped services fails
  • Uses CreateAsyncScope() with await using, scope inside the loop
  • Passes stoppingToken, uses PeriodicTimer
  • Knows unhandled exceptions stop the host since .NET 6 and catches per item

Red flags

  • Injects DbContext directly or resolves it from IServiceProvider
  • One scope for the whole loop
  • No cancellation or error handling

📚 Learn in depth

1. How hosted services are created

AddHostedService<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.

2. Scope per unit of work

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.

3. Failure behaviour

  • .NET 6+: 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.
  • .NET 8+ added HostOptions.ServicesStartConcurrently / ServicesStopConcurrently and IHostedLifecycleService for finer start-up hooks.

4. Cancellation and shutdown

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.

5. Concurrency inside one worker

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.

Try it yourself

  1. Inject AppDbContext into a BackgroundService constructor and run in Development; read the exception.
  2. Implement the per-tick scope version and log the context's hash code each tick to see it change.
  3. Throw inside ExecuteAsync without a try/catch and watch the host stop; then set BackgroundServiceExceptionBehavior.Ignore and notice the silent failure.
  4. Send SIGTERM (docker stop) while processing and confirm the worker stops within the shutdown timeout.

💻 Code

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();

⚠ Common mistakes

  • Mistake: Injecting 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.
  • Mistake: Creating one scope before the 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.
  • Mistake: Injecting IServiceProvider and calling GetRequiredService<AppDbContext>(). Why it is wrong: That resolves from the root provider; Development throws, Production leaks. Instead: CreateAsyncScope() first.
  • Mistake: No try/catch in 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).
  • Mistake: Swallowing 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.
  • Mistake: Long synchronous work before the first 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().
  • Mistake: Sharing one scope across parallel branches. Why it is wrong: The branches share a DbContext and EF throws on concurrent use. Instead: One scope per branch.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions unhandled exceptions stopping the host Why: Checks global exception strategy across ASP.NET Core and background services
    How to answer

    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.

  2. When: Candidate mentions captive dependencies Why: Checks they can diagnose the same bug when it reaches production
    How to answer

    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.

  3. When: Candidate mentions IDbContextFactory or factories Why: Checks factory injection alternatives
    How to answer

    When the container can't build something up front, inject a factory instead of the object.

    • A factory registration (AddScoped<IFoo>(sp => ...)) runs logic at resolution time, for example choosing an implementation from configuration.
    • Unlike Autofac, the built-in container (still true in .NET 10) does not auto-supply Func<T> or Lazy<T>; you register them explicitly.
    • For run-time values, define a small typed factory interface and implement it with 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.

🛠 Real-world problems: how you handle them

Outbox publisher with a constructor-injected DbContext grew to 1.2 GB and stopped the host
Situation
[Order platform, outbox publisher BackgroundService inside the API process on Azure App Service, Australia East, ~50,000 outbox messages a day]. The worker injected AppDbContext directly and the team had set ASPNETCORE_ENVIRONMENT=Production everywhere, so scope validation never ran.
Signals
Working set rose steadily to [~1.2 GB] over [a few days]; outbox lag alerts fired; twice the whole API went down when a malformed message threw inside ExecuteAsync ('BackgroundService failed' then 'Application is shutting down').
Investigation
dotnet-gcdump showed one AppDbContext tracking [~400,000] OutboxMessage entities. Application Insights logs showed the host-stopping exception from the worker. Running locally in Development reproduced the start-up failure 'Cannot consume scoped service AppDbContext from singleton IHostedService'.
Resolution
Rewrote the worker to inject IServiceScopeFactory and create an async scope per 5-second tick, processing at most 200 messages with AsNoTracking reads and a try/catch per message that marks failures for retry and dead-letters after 5 attempts.
Prevention
Enabled ValidateScopes and ValidateOnBuild in all environments; added an integration test that starts the host and runs one tick against a Testcontainers SQL Server; alerts on outbox lag and on the BackgroundService failure log message.

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.

↩ Usually asked after

More in Service Lifetimes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me