Entity Framework Core Interview Question #147

What is DbContext pooling?

Performance, Raw SQL, Stored Procedures & Advanced Queries Senior Advanced

Quick Interview Answer

DbContext pooling allows EF Core to reuse DbContext instances after their internal state has been reset, reducing some context allocation and initialization overhead. It is configured with AddDbContextPool. Because instances are reused, mutable per-request state should not be stored on a pooled context as though a brand-new instance were always created. Use it when its lifetime implications are understood and measurements justify it.

Detailed Explanation

DbContext pooling allows EF Core to reuse DbContext instances after their internal state has been reset, reducing some context allocation and initialization overhead. It is configured with AddDbContextPool. Because instances are reused, mutable per-request state should not be stored on a pooled context as though a brand-new instance were always created. Use it when its lifetime implications are understood and measurements justify it.

Code Example

builder.Services.AddDbContextPool<AppDbContext>(options =>
    options.UseSqlServer(connectionString));