.NET Core

Tutorial: Building a Background Job Processor with .NET 10 BackgroundService: The Scoped Service Trap

Tutorial: Building a Background Job Processor with .NET 10 BackgroundService: The Scoped Service Trap

A BackgroundService is the supported way to run long-lived work inside an ASP.NET Core host. You register it with AddHostedService<T>(), it starts with the app, and it stops when the host shuts down. The part that trips people up is not the loop — it is what you inject into it.

A BackgroundService is registered as a singleton. If you inject a scoped service like DbContext directly into its constructor, you get one instance shared across your entire process lifetime, and with EF Core that eventually throws InvalidOperationException: A second operation was started on this context instance before a previous operation completed. You'll also see stale data, because the context's change tracker keeps growing.

The fix is to inject IServiceScopeFactory, create a scope per unit of work, and resolve scoped services inside that scope. This tutorial builds a working outbox-style job processor in .NET 10 (targeting net10.0) on ASP.NET Core 10, then covers the failure modes that only show up in production: overlapping runs, unhandled exceptions tearing down the loop, and graceful shutdown mid-job.

Prerequisites

  • .NET 10 SDK (dotnet --version should report 10.x)
  • SQL Server LocalDB or SQLite — the examples below use SQLite via Microsoft.EntityFrameworkCore.Sqlite 10.0.0 so you can run them anywhere
  • Understanding of DI lifetimes (Singleton, Scoped, Transient)

Step 1: Define the job and the data model

The pattern only makes sense with a real table. We'll use a Job table acting as a queue:

CSHARP
// Models/Job.cs
namespace JobProcessor.Models;

public class Job
{
    public int Id { get; set; }
    public string Payload { get; set; } = string.Empty;
    public DateTime CreatedAtUtc { get; set; }
    public DateTime? StartedAtUtc { get; set; }
    public DateTime? CompletedAtUtc { get; set; }
    public int Attempts { get; set; }
    public string? LastError { get; set; }
}
CSHARP
// Data/AppDbContext.cs
using JobProcessor.Models;
using Microsoft.EntityFrameworkCore;

namespace JobProcessor.Data;

public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
    public DbSet<Job> Jobs => Set<Job>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Job>(e =>
        {
            e.HasIndex(j => new { j.CompletedAtUtc, j.StartedAtUtc });
            e.Property(j => j.Payload).HasMaxLength(4000).IsRequired();
        });
    }
}

Step 2: Write the worker with a per-batch scope

This is the core of the tutorial. Notice the constructor — IServiceScopeFactory and ILogger, both singletons. Nothing else.

CSHARP
// Workers/JobProcessorWorker.cs
using JobProcessor.Data;
using Microsoft.EntityFrameworkCore;

namespace JobProcessor.Workers;

public sealed class JobProcessorWorker(
    IServiceScopeFactory scopeFactory,
    ILogger<JobProcessorWorker> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        logger.LogInformation("Job processor starting");

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await using var scope = scopeFactory.CreateAsyncScope();
                var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();

                var now = DateTime.UtcNow;
                var batch = await db.Jobs
                    .Where(j => j.CompletedAtUtc == null && j.Attempts < 5)
                    .Where(j => j.StartedAtUtc == null || j.StartedAtUtc < now.AddMinutes(-5))
                    .OrderBy(j => j.Id)
                    .Take(10)
                    .ToListAsync(stoppingToken);

                if (batch.Count == 0)
                {
                    await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
                    continue;
                }

                foreach (var job in batch)
                {
                    job.StartedAtUtc = DateTime.UtcNow;
                    job.Attempts++;
                }
                await db.SaveChangesAsync(stoppingToken);

                foreach (var job in batch)
                {
                    // Simulate work. Replace with your real handler.
                    try
                    {
                        if (job.Payload.Contains("FAIL"))
                            throw new InvalidOperationException("Simulated failure");

                        logger.LogInformation("Processed job {JobId}", job.Id);
                        job.CompletedAtUtc = DateTime.UtcNow;
                        job.LastError = null;
                    }
                    catch (Exception ex)
                    {
                        job.LastError = ex.Message;
                        logger.LogWarning(ex, "Job {JobId} failed on attempt {Attempt}", job.Id, job.Attempts);
                    }
                }
                await db.SaveChangesAsync(stoppingToken);
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Job processor batch failed");
                await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
            }
        }

        logger.LogInformation("Job processor stopped");
    }
}

Three things to observe:

  1. CreateAsyncScope() — this returns AsyncServiceScope, which implements IAsyncDisposable. That matters because DbContext disposes asynchronously. Using the synchronous CreateScope() still works but forces synchronous disposal.
  2. The catch around the batch body — a single unhandled exception in ExecuteAsync in .NET 6+ terminates the entire application, because BackgroundServiceExceptionBehavior.StopHost is the default. That's a common surprise: your job fails once, then your web app goes down.
  3. The stale-job recovery — jobs whose StartedAtUtc is older than five minutes are treated as abandoned. Without this, a crash mid-job leaves the row stuck forever.

Step 3: Register everything correctly

CSHARP
// Program.cs
using JobProcessor.Data;
using JobProcessor.Workers;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<AppDbContext>(o =>
    o.UseSqlite(builder.Configuration.GetConnectionString("Jobs")));

builder.Services.AddHostedService<JobProcessorWorker>();

var app = builder.Build();

// Apply migrations on startup only for development.
using (var scope = app.Services.CreateScope())
{
    scope.ServiceProvider.GetRequiredService<AppDbContext>().Database.EnsureCreated();
}

app.MapGet("/jobs", async (AppDbContext db, CancellationToken ct) =>
    await db.Jobs.OrderByDescending(j => j.Id).Take(20).ToListAsync(ct));

app.Run();

appsettings.json:

JSON
{
  "ConnectionStrings": {
    "Jobs": "Data Source=jobs.db"
  }
}

Run it with dotnet run. Add rows to the Jobs table (any SQLite client works), and within five seconds you'll see log lines like Processed job 1.

Step 4: Configure shutdown and unhandled-exception behaviour

By default, ASP.NET Core gives hosts a 30-second shutdown timeout. If your loop ignores stoppingToken and a job takes 45 seconds, Ctrl+C will terminate the process anyway and you'll lose the in-flight work. You can extend it, but that only delays the problem:

CSHARP
builder.Services.Configure<HostOptions>(o =>
{
    o.ShutdownTimeout = TimeSpan.FromSeconds(20);
    o.BackgroundServiceExceptionBehavior = BackgroundServiceExceptionBehavior.Ignore;
});

⚠️ Common mistake: catching all exceptions is often prescribed as a shortcut, but I'd hold off on BackgroundServiceExceptionBehavior.Ignore unless you've actually logged and handled the failure yourself. It hides problems: your loop keeps running with a corrupted in-memory state instead of failing loudly. The inner try/catch in the code above is usually enough — set Ignore only when you've added catch-all logging you trust.

The shutdown behaviour is worth understanding precisely: when the host stops, StopAsync is called on the hosted service, which cancels stoppingToken and waits up to ShutdownTimeout for ExecuteAsync to return. If it doesn't return in time, the process exits. Your loop must therefore check stoppingToken.IsCancellationRequested at every await point — the Task.Delay and ToListAsync calls above do this automatically.

When not to use this pattern

The BackgroundService in your web app shares its process and lifetime with every HTTP request. That's fine for low-throughput jobs (a few per second, no long-running work). It is not durable: restart the app mid-job and you lose the work unless your database row remembers (as our StartedAtUtc column does). For queues with millions of messages, retries with exponential backoff, dead-lettering, or multi-consumer fan-out, use a real broker — Azure Service Bus, RabbitMQ, or a Postgres SKIP LOCKED queue. The in-process worker is also, by definition, single-machine: every replica of your app starts its own copy, so scale horizontally only if the StartedAtUtc claim above is safe for your workload. It isn't for work that must run exactly once.

If you need multiple workers, use AddHostedService for each; HostOptions.ServicesStartConcurrently (false by default in .NET 8+) controls whether they start sequentially. For most cases leaving it false is correct, because a worker that depends on the database should not start before the database is reachable.

Testing the failure path

Insert a job whose payload contains FAIL and watch the log. The first four attempts log at warning level; the fifth attempt marks it excluded from the query because Attempts < 5 fails, and it quietly stops being retried. There is no dead-letter table here — a real deployment should add one. That gap is intentional; it keeps the tutorial small but you should close it before shipping.

Summary

  • A BackgroundService is a singleton, so inject IServiceScopeFactory (or the new IAsyncServiceScope it creates) and resolve your DbContext inside a per-batch scope. Never inject the context directly.
  • An unhandled exception inside ExecuteAsync stops the entire host by default. Wrap the loop body in a try/catch and log before retrying.
  • Use CreateAsyncScope() rather than CreateScope() when siblings are async-disposable; it enables correct async disposal of DbContext.
  • Respect stoppingToken at every await and set HostOptions.ShutdownTimeout deliberately — the default 30 seconds is the whole budget for graceful shutdown.
  • This approach is a convenience, not a durable queue. If you need guaranteed delivery, visibility timeouts, or exactly-once semantics, use a message broker instead.
Advertisement