skip to content

In an ASP.NET Core 10 app, when do you register AddDbContextFactory instead of AddDbContext, and which lifetimes does each registration use?

level: middleimportance: should knowfreq 45%

answer

  1. work without a request scope
  2. parallel queries inside one request
  3. factory lifetime defaults to Singleton
  4. also registers TContext as Scoped
  5. scoped options under a singleton factory

basics

~20 s

AddDbContext registers the context and its options Scoped, one per request. AddDbContextFactory registers a Singleton factory plus a Scoped context, for code that needs its own short-lived contexts: singletons, parallel queries or several units of work.

solid answer

~40 s

`AddDbContext<TContext>` registers `TContext` and `DbContextOptions<TContext>` as Scoped, which suits ordinary request handling. `AddDbContextFactory<TContext>` registers `IDbContextFactory<TContext>` and the options as Singleton by default, and also registers `TContext` itself as Scoped, created through the factory, so handlers can still inject the context. I choose the factory when code must control context lifetime: a singleton service, two queries run in parallel within one request, or one request that needs separate units of work. Contexts the factory creates belong to the caller, so I wrap them in `await using`. One trap: calling `AddDbContext` with default arguments and then `AddDbContextFactory` leaves the options Scoped under a singleton factory, which fails scope validation in Development; register `AddDbContextFactory` alone, or pass `optionsLifetime: ServiceLifetime.Singleton` to `AddDbContext`.

go deeper

for a junior

Recall that AddDbContextFactory exists for code that needs its own contexts, and that contexts you create from it must be disposed with await using.

for a middle

Lay out the lifetimes each method registers, including the scoped context AddDbContextFactory adds, and name the cases where a request needs more than one context.

for a senior

Spot the scoped-options-under-a-singleton-factory trap from a startup error, and decide when parallel queries are worth the extra connections they open.

for a principal

Set a convention for which code may create contexts explicitly, so factories do not spread into handlers that a plain scoped context serves better.

## Two registrations, two shapes Both extension methods live in EF Core's `EntityFrameworkServiceCollectionExtensions` and both configure the provider through an options callback. They differ in **who owns the context's lifetime**: | | `AddDbContext<TContext>` | `AddDbContextFactory<TContext>` | |---|---|---| | `TContext` | Scoped (`contextLifetime`) | Scoped, created through the factory | | `DbContextOptions<TContext>` | Scoped (`optionsLifetime`) | Singleton (`lifetime`) | | `IDbContextFactory<TContext>` | not registered | Singleton (`lifetime`) | | Who disposes | the request scope | the scope for the injected context; the caller for factory-made contexts | The Scoped `TContext` registration that `AddDbContextFactory` adds is easy to miss: with the factory alone, a Minimal API handler or controller can still take `BookingDbContext` as a parameter and get one per request. (Passing `ServiceLifetime.Transient` as the factory's lifetime makes that context transient too.) ## When the factory is the right call EF Core's documentation recommends the factory wherever the dependency-injection scope does not line up with the unit of work you want. In a web app that means: - **A singleton needs data.** A schedule cache, a rate table or a hosted component that lives for the whole app cannot hold a scoped context, but it can hold the singleton factory and create a context per operation. - **Parallel queries in one request.** A context is not thread-safe, so `Task.WhenAll` over two queries on the injected context throws. Two factory-made contexts can run side by side. - **Several units of work in one request.** An import endpoint that saves each gym class in its own `SaveChangesAsync`, isolating failures, can create a fresh context per item instead of letting one change tracker grow. - **Blazor components**, where the injected scope spans a whole circuit; their pattern belongs to the Blazor material, but the registration is the same call. ## Using factory-made contexts A context from `CreateDbContext()` or `CreateDbContextAsync()` is **not tracked by the container**. The code that created it disposes it: ```csharp app.MapGet("/dashboard", async (IDbContextFactory<BookingDbContext> factory) => { async Task<int> CountAsync(Func<BookingDbContext, Task<int>> query) { await using var db = await factory.CreateDbContextAsync(); return await query(db); } var classes = CountAsync(db => db.GymClasses.CountAsync()); var bookings = CountAsync(db => db.Bookings.CountAsync()); await Task.WhenAll(classes, bookings); return Results.Ok(new { Classes = classes.Result, Bookings = bookings.Result }); }); ``` Each delegate gets its own context, so the two counts can overlap safely, and each context is disposed as soon as its query finishes. ## The double-registration trap Teams that want both the injected context and the factory often write two calls: 1. `AddDbContext<BookingDbContext>(o => ...)` registers `DbContextOptions<BookingDbContext>` as **Scoped**. 2. `AddDbContextFactory<BookingDbContext>(o => ...)` adds a **Singleton** factory, but it only *tries* to add the options, so the scoped registration from step 1 stays. 3. The singleton factory's constructor needs `DbContextOptions<BookingDbContext>`, which is scoped: a captive dependency. In Development, `ValidateOnBuild` and `ValidateScopes` reject it during `builder.Build()`. Two clean ways out: - call **only** `AddDbContextFactory`, which already registers the scoped context for request code; - or keep both calls but pass `optionsLifetime: ServiceLifetime.Singleton` to `AddDbContext`, so the options can be shared by the factory. ## What the factory costs A factory-made context is as cheap to create as an injected one, but each context that runs a query at the same moment holds its own database connection. The parallel dashboard above therefore takes two connections from the driver's pool for one request, and a page that fans out ten queries takes ten. That is often a good trade for a slow dashboard, and a bad one on an endpoint that serves hundreds of requests a second. Some guidelines: - prefer one scoped context and sequential awaits for ordinary endpoints; - reserve parallel factory-made contexts for a few expensive, independent queries; - never hand a factory-made context to code that outlives the `await using` block that created it. ## What stays the same The provider call (`UseNpgsql`, `UseSqlServer`), the connection string from configuration and the context's `DbContextOptions<TContext>` constructor are identical under both registrations. Pooling is a separate choice (`AddDbContextPool` and `AddPooledDbContextFactory`) with its own constraints.

  • With only AddDbContextFactory registered, can a controller still inject BookingDbContext directly, and who disposes it?
    Yes. `AddDbContextFactory` also registers `BookingDbContext` as Scoped, built by calling the factory, so the controller receives one context per request. Because the container created it, the request scope disposes it at the end of the request, exactly as with `AddDbContext`. Only contexts you create yourself through `CreateDbContext` or `CreateDbContextAsync` are yours to dispose.
  • Why does the factory default to Singleton rather than Scoped?
    Its whole point is to be usable from code that has no request scope or outlives one, such as singleton services. A Singleton factory can be injected anywhere; it holds singleton options and creates independent contexts on demand. You can pass a shorter `lifetime`, but then singletons can no longer depend on it.

  • AddDbContextFactory makes the injected DbContext itself a singleton.
  • Contexts created by the factory are disposed automatically by the container.
  • With AddDbContextFactory you can no longer inject the context into controllers.
  • Call AddDbContext and AddDbContextFactory with defaults; they combine without issues.
  • The factory is only for Blazor and has no use in an API.