Course outline

ASP.NET Core / Advanced: Verification and Reliable Operations / Lesson 21

Hosted work, scopes and graceful shutdown

Run background work with owned dependency scopes, cancellation and a recovery plan for interrupted jobs.

About 4 min readContent reviewed
On this page

Lesson goals

  • Create a scope for scoped services used by a hosted service.
  • Respect cancellation and define a bounded shutdown.
  • Distinguish graceful shutdown from durable delivery.

Understand service ownership

A hosted service is managed by the host and can outlive any individual HTTP request. Do not capture a request-scoped dependency or user context for its entire lifetime. Create a scope for a bounded unit of work, resolve the scoped services from that scope, and dispose it when the work ends. Pass stable identifiers and explicit authorization context where appropriate rather than retaining an incoming request object.

Create a scope per unit

The illustrative BackgroundService creates an asynchronous scope for each iteration and resolves an application-defined processor. The processor and its registration are not included; its operation must honor cancellation and own its persistence semantics. Delay prevents a tight polling loop when idle, but an actual queue may supply its own waiting behavior. Observe exceptions and choose a deliberate retry policy rather than swallowing failures indefinitely.

csharp Create a scope inside a hosted worker
public sealed class Worker(IServiceScopeFactory scopes) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await using (var scope = scopes.CreateAsyncScope())
            {
                var processor = scope.ServiceProvider.GetRequiredService<IWorkProcessor>();
                await processor.ProcessAsync(stoppingToken);
            }
            await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
        }
    }
}

IWorkProcessor and its registration are application-defined. The delay is illustrative; production retry and queue behavior require a separate policy.

Honor cancellation and cleanup

When the host requests shutdown, the stopping token signals the service to stop. Finish or interrupt work according to the application’s contract and host shutdown budget, release scoped resources, and avoid starting new work after cancellation. The second fragment shows a processor accepting a cancellation token. A process can still be killed abruptly, so cleanup callbacks and graceful shutdown cannot be the sole recovery mechanism for critical work.

csharp Pass cancellation to a bounded operation
public interface IWorkProcessor
{
    Task ProcessAsync(CancellationToken cancellationToken);
}

The processor implementation owns the real work and cleanup. Cancellation is cooperative and does not guarantee an abrupt process kill runs cleanup.

Design replay-safe work

If a job must survive process termination, persist or use a durable queue with acknowledgement and retry semantics appropriate to the application. A worker may stop after an external effect but before acknowledgement, causing redelivery. Use a stable operation identifier and an idempotent effect or reconciliation procedure. Define a poison-message policy and monitor failed or old jobs without logging credentials or sensitive payloads.

Test stop and recovery

In a controlled host, test scope creation and disposal for two work items, cancellation during a pending operation and bounded shutdown. Simulate process interruption at the commit and acknowledgement boundaries using disposable infrastructure. Verify that a recovered job completes and a duplicate does not repeat its business effect. An in-process test of StopAsync does not prove the production orchestrator’s termination grace period or broker behavior.

Common errors and fixes

A scoped database context leaks between jobs

Why it happens
A hosted singleton retained a scoped dependency.
How to fix it
Create and dispose a scope for each bounded unit of work.
Prevent it next time
Test two jobs and scope disposal.

A job vanishes when the process stops

Why it happens
An in-memory task was treated as durable.
How to fix it
Record work in a durable store or queue and define recovery.
Prevent it next time
Simulate abrupt termination and restart.

A retry repeats an external action

Why it happens
The first attempt completed before acknowledgement was lost.
How to fix it
Use idempotency or reconcile uncertain outcomes.
Prevent it next time
Test duplicate delivery with the same operation identifier.

2 practice exercises

1. Why should a hosted service create a scope for a scoped database context?

Show worked solution

The hosted service can live for the host lifetime, whereas the database context owns a shorter unit of work. Resolve it inside an owned scope and dispose the scope after the work item; do not share mutable context state across jobs.

2. A worker is killed after sending an email but before acknowledging the job. What must be considered?

Show worked solution

The queue may deliver the job again. Graceful shutdown cannot repair an abrupt kill. Use an idempotency mechanism supported by the effect owner or a reconciliation process, and test the uncertain-outcome window.

Key takeaways

  • Hosted services must own short-lived scopes and cooperate with cancellation.
  • Durable work still needs recovery and idempotency after abrupt termination.

Official references