In EF Core, when should code take an IDbContextFactory<TContext> instead of an injected context, and what does AddPooledDbContextFactory register and change?
answer
- caller creates, caller disposes
- CreateDbContextAsync(CancellationToken)
- factory is a singleton
- pooled factory also registers scoped TContext
- scoped wrapper sets per-lease state
basics
~20 sTake IDbContextFactory<TContext> when the code's lifetime does not match one context: singletons, background jobs, parallel branches, long-lived UI sessions. The caller creates and disposes each context. AddPooledDbContextFactory backs the factory with a context pool and also registers a scoped TContext.
solid answer
~40 sAn injected context lives for one dependency-injection scope, which fits a request. `IDbContextFactory<TContext>` lets code create a context per unit of work instead: `CreateDbContext()` or `CreateDbContextAsync(CancellationToken)`, with the caller responsible for `await using`. Use it in singletons and background services, for parallel branches that each need an instance, and in an admin UI that keeps a scope open across many actions. `AddPooledDbContextFactory<TContext>` registers a singleton `IDbContextFactory<TContext>` backed by a pool of up to 1024 retained instances, plus a scoped `TContext` resolved through that factory; disposing a factory-made context returns it to the pool. Pooled contexts cannot take scoped services, so per-request values such as a tenant id are set by a scoped wrapper factory after renting.
code
csharp · 14 linesbuilder.Services.AddPooledDbContextFactory<NewsContext>(
o => o.UseNpgsql(builder.Configuration.GetConnectionString("news")));
public sealed class PublishArticle(IDbContextFactory<NewsContext> factory)
{
public async Task RunAsync(int articleId, CancellationToken ct)
{
await using var db = await factory.CreateDbContextAsync(ct);
var article = await db.Articles.FindAsync([articleId], ct);
if (article is null) return;
article.Published = true;
await db.SaveChangesAsync(ct);
} // DisposeAsync returns the instance to the pool
}go deeper
Recall that IDbContextFactory<TContext> creates contexts on demand and that you dispose each one with await using.
Explain when a factory beats an injected context: singletons, background jobs, parallel branches, long-lived UI sessions.
Describe what AddPooledDbContextFactory registers, how disposal returns instances to the pool, and the scoped wrapper pattern for tenant state.
Choose a context-acquisition policy across request, admin and background workloads, balancing pooling gains against statelessness and clarity of ownership.
## Two ways to get a context An **injected context** is resolved from a dependency-injection scope: one instance per scope, disposed with it. In a web request that is a perfect fit. Some code does not live inside a single short scope, and for that code EF Core provides **`IDbContextFactory<TContext>`**: ```csharp public interface IDbContextFactory<TContext> where TContext : DbContext { TContext CreateDbContext(); Task<TContext> CreateDbContextAsync(CancellationToken cancellationToken = default) => Task.FromResult(CreateDbContext()); } ``` Each call returns a **new context owned by the caller**, which must dispose it, normally with `await using`. ## When the factory is the right tool | Situation | Why an injected context fails | Factory approach | |---|---|---| | Singleton service or `BackgroundService` | It would capture one context for the app's life | Create a context per job or message | | Parallel branches (`Task.WhenAll`) | One instance cannot run two operations at once | One context per branch | | A long-lived UI session, such as an admin screen that stays open | The scope outlives many independent actions and the tracker keeps growing | One context per action | | Short units inside a long request | The scoped instance accumulates tracked entities | A fresh context per unit | In the news scenario, the public API serves requests with an injected pooled `NewsContext`, while the **admin UI** creates a context per editor action from the factory: publish an article, then dispose; rebuild a section, then dispose. ## What AddPooledDbContextFactory registers `AddPooledDbContextFactory<TContext>(optionsAction, poolSize = 1024)` sets up three services: 1. a singleton `IDbContextPool<TContext>`, the pool itself; 2. a singleton **`IDbContextFactory<TContext>`**, implemented by `PooledDbContextFactory<TContext>`, which rents from that pool; 3. a **scoped `TContext`**, resolved by calling the factory, so ordinary constructor injection keeps working. So one registration serves both styles: request code injects `NewsContext`, the admin and background code inject `IDbContextFactory<NewsContext>`. Disposing a context that came from the pooled factory **returns it to the pool** after the usual reset. The same pooling rules apply as with `AddDbContextPool`: frozen singleton options, one public constructor taking `DbContextOptions`, extra constructor parameters only from the root provider, and `poolSize` as a retention limit rather than a cap. Outside dependency injection, `new PooledDbContextFactory<NewsContext>(options, poolSize)` gives the same pooled factory directly. ## Per-request state on pooled contexts A pooled context cannot take a scoped service in its constructor, and its `OnConfiguring` runs once per instance, so neither can carry a **tenant id**. The EF documentation's pattern is a **scoped wrapper factory**: 1. Register the pooled factory as usual with `AddPooledDbContextFactory<NewsContext>(...)`. 2. Write a scoped `IDbContextFactory<NewsContext>` implementation that takes the singleton pooled factory and the scoped tenant service, calls `CreateDbContext()` on the pooled one, and sets `context.TenantId` before returning it. 3. Register that wrapper as a scoped service under its own class type, so it does not collide with the pooled `IDbContextFactory<NewsContext>` it wraps, and register `NewsContext` as scoped through the wrapper's `CreateDbContext()`. ```csharp public sealed class TenantNewsContextFactory( IDbContextFactory<NewsContext> pooled, ITenant tenant) : IDbContextFactory<NewsContext> { public NewsContext CreateDbContext() { var context = pooled.CreateDbContext(); context.TenantId = tenant.TenantId; return context; } } ``` Every lease then has its value set again, and a value from an earlier request never survives, because the wrapper overwrites it each time. Take the tenant from a trusted source; it decides which rows a global query filter exposes. ## Factory or a new scope? A background worker could also create a dependency-injection scope per job with `IServiceScopeFactory` and resolve the context from it. That is the right choice when the job needs **several scoped services** that must share one context. When the job needs only data access, the factory is simpler: no scope object, an explicit `await using` on the one thing that needs disposing, and no chance of resolving other scoped services by accident. Both approaches give each job its own context; what matters is that no context is shared across jobs or threads. ## Pitfalls - **Forgetting to dispose.** A factory-made context is not tracked by any scope. Without `await using` it never returns to the pool and its resources wait for the garbage collector. - **Disposing an injected context.** The scope owns that one; disposing it yourself leads to "Cannot access a disposed context instance" later in the request. - **Keeping a factory-made context in a field.** That recreates the long-lived context the factory was meant to avoid. - **Assuming the async method opens a connection.** `CreateDbContextAsync` only creates or rents the instance; connections still open per operation.
- Can a controller still inject NewsContext when only AddPooledDbContextFactory was called?Yes. `AddPooledDbContextFactory` also registers `NewsContext` as a scoped service resolved through the factory, so constructor injection works and the scope disposes the instance, returning it to the pool. Code that needs its own instances injects `IDbContextFactory<NewsContext>` from the same registration.
- Does CreateDbContextAsync do real asynchronous work?The interface's default implementation just wraps `CreateDbContext()` in a completed task. `PooledDbContextFactory` overrides it to rent from the pool through the async lease path. Either way it does not open a database connection; that still happens per operation.
- Contexts from IDbContextFactory are disposed automatically at the end of the request.
- AddPooledDbContextFactory registers only the factory, so NewsContext can no longer be injected.
- A pooled context's constructor is the right place to inject the scoped tenant service.
- CreateDbContextAsync opens the database connection before returning the context.
- IDbContextFactory<TContext> is registered as scoped by default, so it cannot be used in a singleton.