wasAsked.

Can DBcontext with register as singleton?

Agiliad Technologies Pvt Ltd · Role not specified · technical

Published

Asked in 2026 · .NET, C#, Entity Framework Core

Community answers

Posted by wasAsked editorial collection

Technically you can register a DbContext as a singleton, but you should not. DbContext is designed to be a short-lived unit of work, and AddDbContext registers it as scoped (one instance per HTTP request) for good reasons. Problems with a singleton DbContext: - It is not thread-safe. Concurrent requests share one instance, which causes "A second operation was started on this context instance before a previous operation completed" and corrupted state. - The change tracker keeps every entity it has ever loaded, so memory grows for the life of the application and later queries return stale tracked data. - A failed SaveChanges leaves the context in a bad state that affects every later request. - Scoped services that depend on it (or that it depends on) cause captive-dependency problems. Correct options: - Web apps: services.AddDbContext<AppDbContext>(...) — scoped per request. - High-throughput apps: services.AddDbContextPool<AppDbContext>(...) reuses instances safely by resetting them between requests. - Singletons and background services that need the database: inject IDbContextFactory<AppDbContext> and create a short-lived context per operation. public sealed class ReportWorker(IDbContextFactory<AppDbContext> factory) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken ct) { await using var db = await factory.CreateDbContextAsync(ct); var pending = await db.Reports.Where(r => !r.Sent).ToListAsync(ct); // ... } } Alternatively, inject IServiceScopeFactory and create a scope per unit of work. Summary for the interview: DbContext should be scoped or created per operation, never a singleton; use pooling or a factory when you need performance or access from a singleton.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics