What is DbContext pooling in EF Core?
Quick Answer
AddDbContextPool<T>() keeps a pool of DbContext instances and reuses them across requests instead of constructing a new one each time. EF resets the context's state (change tracker, etc.) before handing it back. It's a micro-optimisation for high-throughput apps — the context is still effectively scoped per request.
AddDbContextPool reuses DbContext instances from a pool instead of building a fresh one for every request. EF wipes the change tracker and other state before it's reused, so from my code's point of view it still behaves like a per-request context. It's a throughput optimisation — it removes the small per-request construction cost. The catch is that the context can't take per-instance dependencies in its constructor, like a tenant id, because that would carry over to the next request that borrows the same instance. So if I need context-specific state I stick with plain AddDbContext.
- Constructing a
DbContextis cheap but not free — model metadata is cached, but there's still per-instance setup. Pooling removes that per-request cost. - Register with
builder.Services.AddDbContextPool<AppDbContext>(o => ...)and an optionalpoolSize. - Constraint: the context can't have per-instance state injected through its constructor beyond
DbContextOptions(e.g. a tenant id or current-user), because that state would leak between pooled uses. UseAddDbContext(no pool) or resolve such state differently if you need it. - Measure before adopting — the benefit shows up under real load, not in a demo.