Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 41 ยท Testing and Patterns

DbContext in ASP.NET Core and Dependency Injection

Register DbContext in ASP.NET Core, understand scoped lifetime, why contexts are not thread-safe, when to use IDbContextFactory, pooling and background services, with stand-ins.

In a web application you almost never write new AppDbContext() yourself. You ask the framework for one, and ASP.NET Core's dependency injection (DI) container creates it, hands it to your code and disposes it. Getting the lifetime right is the difference between a stable app and one with mysterious InvalidOperationExceptions, stale data and memory growth.

EF Core and ASP.NET Core code is read-only on this site; the runnable blocks are stand-ins that model lifetimes in plain C#.

Registering the context

C#
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<ShopContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("Shop")));

var app = builder.Build();

app.MapGet("/products/{id:int}", async (int id, ShopContext db) =>
    await db.Products.FindAsync(id) is { } p ? Results.Ok(p) : Results.NotFound());

AddDbContext registers the context as scoped by default. In a web app one scope = one HTTP request: every class asking for ShopContext during that request gets the same instance, and it is disposed when the request ends. This is exactly what you want:

  • All code in a request shares one change tracker, so entities loaded in a service are visible in another (see change tracking basics).
  • A single SaveChangesAsync() commits everything in one transaction.
  • Different requests never share a context, so tracked state never leaks between users.

The context constructor receives the options (see DbContext and DbSet):

C#
public class ShopContext(DbContextOptions<ShopContext> options) : DbContext(options)
{
    public DbSet<Product> Products => Set<Product>();
}
C# Stand-in: scoped lifetime, one instance per request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A DbContext is not thread-safe

One context instance must never be used by two threads at once. The most common way to break this rule is to start two async operations on the same context without awaiting the first:

C#
// WRONG: both queries run on one context at the same time
var a = db.Products.CountAsync();
var b = db.Orders.CountAsync();
await Task.WhenAll(a, b);   // InvalidOperationException: a second operation was started on this context

// RIGHT: await them one after the other
var products = await db.Products.CountAsync();
var orders = await db.Orders.CountAsync();

If you really need parallel database work, give each task its own context (see the factory below).

C# Stand-in: detecting concurrent use of one context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

IDbContextFactory: when there is no request scope

Some code has no request scope: background services (BackgroundService, hosted services are singletons), Blazor Server components (a long-lived circuit), desktop apps, or parallel tasks. Injecting a scoped context into a singleton fails, and keeping one context alive for hours causes stale data and growing memory because the tracker holds every entity it ever loaded.

Use a factory and create a short-lived context per unit of work:

C#
builder.Services.AddDbContextFactory<ShopContext>(o => o.UseSqlServer(connectionString));

public class NightlyCleanup(IDbContextFactory<ShopContext> factory) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await using var db = await factory.CreateDbContextAsync(stoppingToken);
            await db.Orders
                .Where(o => o.Status == OrderStatus.Abandoned && o.CreatedAt < DateTime.UtcNow.AddDays(-30))
                .ExecuteDeleteAsync(stoppingToken);

            await Task.Delay(TimeSpan.FromHours(24), stoppingToken);
        }
    }
}

Rule: create the context, do one unit of work, dispose it. Inside a request-scoped service you can also call factory.CreateDbContext() for parallel queries, each with its own instance.

You can also register a scoped context built by the factory with AddDbContextFactory plus AddScoped(sp => sp.GetRequiredService<IDbContextFactory<ShopContext>>().CreateDbContext()) when you need both styles.

Pooling

Creating a context is cheap but not free: EF Core must set up services and the model reference for each instance. Context pooling reuses instances:

C#
builder.Services.AddDbContextPool<ShopContext>(o => o.UseSqlServer(connectionString), poolSize: 256);

On dispose, EF Core resets the instance (clears the tracker) and returns it to a pool. This saves allocations on busy APIs. Caveats: the context must not hold per-request state in fields (for example a current-tenant ID set in the constructor), because the same instance will serve other requests. Pass per-request values through a scoped service that the context reads at query time instead. See compiled queries, split queries and pooling.

Lifetime mistakes to avoid

flowchart LR
    S["Singleton service"] -->|"injects scoped DbContext"| X["Captive dependency: one context lives forever"]
    R["Scoped service"] -->|"injects DbContext"| OK["Correct: context lives one request"]
    S2["Singleton or BackgroundService"] -->|"injects IDbContextFactory"| OK2["Correct: create per unit of work"]

A longer-lived object must not hold a shorter-lived one. ASP.NET Core's validation (on in Development) throws when you try.

  • Captive dependency: a singleton that takes ShopContext in its constructor keeps one context forever. Inject the factory instead.
  • Static or cached contexts: never store a context in a static field.
  • Disposing a DI-created context yourself: do not wrap an injected context in using; the container owns it.
  • Returning IQueryable from a scoped service after the scope ends: materialize (ToListAsync) before the request finishes.
  • Fire-and-forget tasks that use the request's context after the response was sent: the context may already be disposed. Create a new scope or use a factory.

Configuration tips

  • Keep the connection string in configuration, not in OnConfiguring, so tests and environments can override it.
  • Turn on EnableSensitiveDataLogging() and EnableDetailedErrors() only in Development.
  • Add a retry on failure strategy for cloud databases: sql.EnableRetryOnFailure() (see pessimistic locking and isolation levels).
  • Resolve long-running read-only endpoints with AsNoTracking by default if they never save (see query performance).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the default lifetime of a context registered with AddDbContext?

    Scoped means one instance per HTTP request, shared by all services in that request and disposed at the end.
  2. 2. What happens if two async operations run at the same time on one context?

    A DbContext supports one operation at a time. Await each call, or use a separate context per task.
  3. 3. How should a BackgroundService get a DbContext?

    Hosted services are singletons, so a scoped context would be a captive dependency. The factory creates short-lived contexts.
  4. 4. What is a risk of AddDbContextPool?

    Pooled instances are reused, so do not store request-specific values in fields; read them from a scoped service instead.

Summary

  • AddDbContext registers a scoped context: one per request, disposed automatically.
  • A context is not thread-safe: await every call, and use one context per parallel task.
  • Use IDbContextFactory in background services, Blazor Server and anywhere without a request scope.
  • Pooling saves allocations but forbids per-request state in context fields.
  • Never let a long-lived object hold a short-lived context.

Next: Global query filters, interceptors and specifications