Entity Framework Core Interview Question #148

What is IDbContextFactory and when is it useful?

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

Quick Interview Answer

IDbContextFactory creates DbContext instances on demand. It is useful when a DI scope does not naturally correspond to one unit of work or when separate contexts are needed in background work, UI components, or carefully designed parallel operations. Each created context should be disposed. A DbContext itself is not thread-safe and should not be shared concurrently.

Detailed Explanation

IDbContextFactory creates DbContext instances on demand. It is useful when a DI scope does not naturally correspond to one unit of work or when separate contexts are needed in background work, UI components, or carefully designed parallel operations. Each created context should be disposed. A DbContext itself is not thread-safe and should not be shared concurrently.

Code Example

await using var db =
    await dbContextFactory.CreateDbContextAsync();

var count = await db.Products.CountAsync();