Covers the concurrency contract each lifetime implies: thread-safe singletons, scoped services shared by parallel work within one request, DbContext concurrent use, and how message consumers and parallel processing need a scope per concurrent unit.
Lifetimes imply a concurrency contract. A singleton is used by every request at the same time, so its state must be immutable, concurrent (ConcurrentDictionary, Interlocked) or locked. A scoped service is per scope, not per thread: inside one request, Task.WhenAll or Parallel.ForEachAsync branches get the same scoped instances, so a DbContext shared by parallel branches throws "A second operation was started on this context instance". The same error comes from a missing await or fire-and-forget work using request services after the response (often ObjectDisposedException).
The rule: one scope per concurrent unit of work. For parallel database work use IDbContextFactory<T> (a context per branch); for message consumers with concurrency above 1, a scope per in-flight message. Trade-off: more scopes means more connections, so bound the parallelism.
"I think of each lifetime as a promise about concurrency. A singleton says 'many threads, at once, for ever', so anything mutable in it has to be thread-safe: immutable data, concurrent collections,
Interlocked, or a lock around compound operations. Transient says 'nobody else has this instance', which is the safest. Scoped is the one people get wrong: it means one instance per scope, not per thread. In a request, the scope is shared by everything in that request, including parallel tasks you start yourself.That's why you can get 'A second operation was started on this context instance' even when the
DbContextis correctly scoped. The classic cause isTask.WhenAllover three repository calls in one handler: three branches, one context. A missingawaitdoes the same thing more subtly, and fire-and-forget is worse: the request finishes, the scope disposes the context, and the background task getsObjectDisposedException. For example, at [company] we [had a dashboard endpoint that loaded four widgets in parallel] and [about 1% of requests] failed with that error; giving each branch its own context fromIDbContextFactory<T>fixed it and [kept the latency gain of running in parallel].In message consumers the scope is per message. If the consumer runs with a concurrency limit of 16, that's 16 scopes and 16 contexts in flight, which is correct, but it also means 16 connections, so I size the pool and the concurrency together. The one-line rule I give teams: one scope per concurrent unit of work, and singletons must be safe for every request at once."
| Lifetime | Who uses it concurrently | Requirement |
|---|---|---|
| Singleton | All requests and workers | Thread-safe state |
| Scoped | Everything in one scope, including your own parallel tasks | Don't share across parallel branches unless thread-safe |
| Transient | Only its consumer | Safe unless the consumer shares it |
| Cause | Fix |
|---|---|
Task.WhenAll over calls on one context |
Context per branch (IDbContextFactory<T>) or sequential awaits |
Missing await |
Await every call; enable CA2012/CS4014 warnings as errors |
async void event handler using the context |
async Task, awaited |
| Fire-and-forget using request services | New scope inside the background work; better, a queue |
| Captive context in a singleton | Fix the lifetime |
| Host | Scope | Concurrency |
|---|---|---|
| ASP.NET Core request | One per request | Many requests in parallel, each isolated |
| Queue consumer (concurrency N) | One per message | N scopes in flight |
Batch job with Parallel.ForEachAsync |
You decide | One scope per branch, bounded MaxDegreeOfParallelism |
The dashboard endpoint went from [~1%] 'second operation' failures to zero, and kept a p95 of [180 ms] versus [520 ms] for the sequential version. Connection pool usage peaked at [4 per request], which we had sized for at [~100 concurrent requests per instance].
Checks that the candidate links lifetimes to concurrency correctly, especially that scoped is per scope rather than per thread.
Green flags
Task.WhenAll exampleIDbContextFactory<T> for parallel branchesRed flags
DbContextTask.Run with request services after the responseRequest scope
├─ handler (scoped) ──┐
├─ repoA (scoped) ──┼── all share AppDbContext #1
└─ repoB (scoped) ──┘
Task.WhenAll(repoA.LoadAsync(), repoB.LoadAsync())
thread X: AppDbContext #1 query A ─┐ overlap → InvalidOperationException
thread Y: AppDbContext #1 query B ─┘
Async continuations can run on any thread-pool thread; the scope follows the logical flow (HttpContext.RequestServices), not a thread.
DbContext uses a ConcurrencyDetector that marks an operation in progress. A second entry while one is active throws immediately. It is not a lock; it is a guard that converts silent corruption of the connection and change tracker into a clear exception. It only fires when operations actually overlap, so the error rate rises with load and latency.
| State | Pattern |
|---|---|
| Read-only after start-up | Immutable types, FrozenDictionary |
| Counters | Interlocked.Increment |
| Key-value cache | ConcurrentDictionary (beware GetOrAdd factory running twice) or IMemoryCache |
| Compound updates | lock or SemaphoreSlim (async) around the whole operation |
| Refreshable snapshot | Swap a reference atomically (Volatile.Write / Interlocked.Exchange) |
request → _ = Task.Run(() => service.DoAsync()) // captures scoped service
response sent → scope disposed → DbContext disposed
background task → ObjectDisposedException
Correct: enqueue to a Channel<T> consumed by a BackgroundService that creates its own scope per item.
Each concurrent scope with a DbContext may hold a pooled connection. SQL Server's ADO.NET pool defaults to Max Pool Size=100. Concurrency per instance × connections per unit must stay under it, or requests queue for connections (timeouts after 15 seconds by default).
Task.WhenAll on one context; load test it and count exceptions.IDbContextFactory<T> per branch and compare latency to sequential awaits.await and see the analyser warning (CS4014) and the runtime failure.Dictionary<,> from 32 threads and watch it corrupt or throw; switch to ConcurrentDictionary.Parallel reads in one request: wrong and right.
using Microsoft.EntityFrameworkCore;
namespace Dashboard;
public sealed record Widget(string Name, int Value);
public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<Order> Orders => Set<Order>();
public DbSet<Customer> Customers => Set<Customer>();
}
public sealed class Order { public int Id { get; set; } public bool Open { get; set; } }
public sealed class Customer { public int Id { get; set; } public bool Active { get; set; } }
// WRONG: two operations overlap on the request's single scoped context.
public sealed class DashboardServiceBroken(AppDbContext db)
{
public async Task<Widget[]> LoadAsync(CancellationToken ct)
{
var orders = db.Orders.CountAsync(o => o.Open, ct);
var customers = db.Customers.CountAsync(c => c.Active, ct); // second operation → throws
await Task.WhenAll(orders, customers);
return [new("Open orders", orders.Result), new("Active customers", customers.Result)];
}
}
// RIGHT: one short-lived context per concurrent branch.
public sealed class DashboardService(IDbContextFactory<AppDbContext> contexts)
{
public async Task<Widget[]> LoadAsync(CancellationToken ct)
{
var orders = CountAsync(db => db.Orders.CountAsync(o => o.Open, ct), ct);
var customers = CountAsync(db => db.Customers.CountAsync(c => c.Active, ct), ct);
var results = await Task.WhenAll(orders, customers);
return [new("Open orders", results[0]), new("Active customers", results[1])];
}
private async Task<int> CountAsync(Func<AppDbContext, Task<int>> query, CancellationToken ct)
{
await using var db = await contexts.CreateDbContextAsync(ct);
return await query(db);
}
}
Thread-safe singleton state and fire-and-forget done properly:
using System.Collections.Concurrent;
using System.Threading.Channels;
namespace Dashboard;
public sealed class HitCounter
{
private readonly ConcurrentDictionary<string, long> _hits = new();
public void Hit(string path) => _hits.AddOrUpdate(path, 1, static (_, n) => n + 1);
public long Get(string path) => _hits.GetValueOrDefault(path);
}
public sealed record AuditEvent(string UserId, string Action);
// Request code writes to the channel and returns; never Task.Run with scoped services.
public sealed class AuditQueue
{
private readonly Channel<AuditEvent> _channel = Channel.CreateBounded<AuditEvent>(10_000);
public ValueTask EnqueueAsync(AuditEvent e, CancellationToken ct) => _channel.Writer.WriteAsync(e, ct);
public IAsyncEnumerable<AuditEvent> ReadAllAsync(CancellationToken ct) => _channel.Reader.ReadAllAsync(ct);
}
public interface IAuditWriter { Task WriteAsync(AuditEvent e, CancellationToken ct); }
public sealed class AuditWorker(AuditQueue queue, IServiceScopeFactory scopes) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var e in queue.ReadAllAsync(stoppingToken))
{
await using var scope = scopes.CreateAsyncScope(); // own scope, not the dead request's
await scope.ServiceProvider.GetRequiredService<IAuditWriter>().WriteAsync(e, stoppingToken);
}
}
}
Task.WhenAll over several queries on one DbContext for speed. Why it is wrong: EF throws on overlapping operations. Instead: IDbContextFactory<T> per branch, or one combined query.Task.Run or _ = DoAsync() with request services after returning a response. Why it is wrong: The scope disposes them; you get ObjectDisposedException or worse, half-finished writes. Instead: A Channel<T> plus a worker with its own scopes, or a durable queue.Dictionary<,> or List<> in a singleton without synchronisation. Why it is wrong: Concurrent writes corrupt internal state, causing infinite loops or lost entries. Instead: Concurrent collections, immutable snapshots or locks.DbContext. Why it is wrong: It serialises the work and still mixes change trackers. Instead: Separate contexts.Max Pool Size requests queue and time out. Instead: Size concurrency and pool together.When I review concurrency in DI-based code I map every concurrent flow to a scope. Requests already have one. Messages need one each. Parallel branches I create need one each. Anything that outlives the request needs its own. Singletons are reviewed like shared memory, because that's what they are. The particularly dangerous bug is per-request identity in a singleton: it's not just wrong data, it can show one customer's information to another, which in Australia is a potential eligible data breach under the Notifiable Data Breaches scheme.
| Approach | When it fits | Cost | When not to |
|---|---|---|---|
| Sequential awaits on one context | Few, fast queries | Latency adds up | Many independent slow queries |
IDbContextFactory<T> per branch |
Independent parallel reads | One connection per branch | Writes that must commit together |
| One combined query / projection | Related data | Query complexity | Unrelated data sets |
| Scope per message | Consumers | Connection per in-flight message | Shared transaction across messages |
Channel<T> + worker for background work |
Post-response work | In-memory: lost on crash | Work that must survive restarts (use a durable queue / outbox) |
I verify with a load test at expected concurrency and track EF concurrency exceptions, connection pool wait time (Microsoft.Data.SqlClient event counters) and p95 latency.
A DbContext wraps one connection and one change tracker and allows one operation at a time; EF's concurrency detector throws when a second async operation starts before the first completes, usually from a shared context or a missing await. To run work in parallel, give each branch its own context (IDbContextFactory<T>.CreateDbContextAsync()), or combine the queries into one round trip. Never share a context across Task.WhenAll branches.
System.Collections.Concurrent types are safe for many threads at once. ConcurrentDictionary uses lock-free reads and fine-grained (striped) locks for writes. Each single method is atomic, but check-then-act across two calls is not, so use GetOrAdd, AddOrUpdate, TryUpdate or TryRemove. Caveat: the value factory in GetOrAdd/AddOrUpdate can run more than once under contention (only one result is stored), so wrap expensive or side-effecting work in Lazy<T>. Count, IsEmpty and ToArray take every lock, so avoid them in hot paths. ConcurrentQueue/ConcurrentStack are lock-free FIFO/LIFO. ConcurrentBag is unordered, optimised for the same thread adding and taking. BlockingCollection adds bounding and blocking Take but blocks threads; for async producer/consumer use Channel<T>.
AddHostedService<T>() registers the worker as a singleton, so a scoped DbContext in its constructor would be a captive dependency: one context for the life of the process (Development throws at start-up). Instead, inject IServiceScopeFactory and create a scope per unit of work:
await using var scope = scopes.CreateAsyncScope();
var svc = scope.ServiceProvider.GetRequiredService<IOrderService>();
Each message or tick gets a fresh context that is disposed at the end. Pass stoppingToken everywhere, use PeriodicTimer for polling, and catch exceptions per item: since .NET 6 an unhandled exception in ExecuteAsync stops the host by default. If only a context is needed, IDbContextFactory<T> is simpler. Trade-off: smaller scopes mean fresher state and less memory, but more allocations per item.
How to tell it (STAR)
**S:** At [company], our operations dashboard started failing for [about 1 in 25] users at the morning peak right after a performance change. **T:** I needed to keep the latency improvement but remove the failures. **A:** The exceptions were all EF's 'second operation' error from one service. The change had started four queries in parallel with Task.WhenAll on the request's scoped DbContext; scoped means one per request, not per thread, so the branches collided under load. I reproduced it with k6, then gave each branch its own short-lived context from IDbContextFactory and checked connection usage stayed well under the pool limit. **R:** Failures went to zero, p95 stayed at [180 ms] instead of the [520 ms] sequential version, and the load test now runs on every release.
Last updated 23 Nov 2026.