Covers a decision process for choosing singleton, scoped or transient based on state, thread safety, construction cost and dependencies, with the standard choices for DbContext, HttpClient, caches and stateless services.
I choose by state and thread safety, then check dependencies:
So: DbContext is scoped (not thread-safe, one unit of work), or created per operation with IDbContextFactory<T> outside requests. HttpClient comes from IHttpClientFactory (pooled handlers, DNS refresh) or is one singleton with PooledConnectionLifetime. IMemoryCache is a singleton. The trade-off is sharing versus safety: wider lifetimes save allocations but demand thread safety and stricter dependencies.
"I run through four questions. First, does it hold state, and whose state is it? If it's per request or per message, like an EF change tracker or the current tenant, it's scoped. Second, if it's shared state, is it safe for many threads to use at once? A cache or an
IHttpClientFactoryis designed for that, so it's a singleton. Third, is it expensive to build? A compiled regex set or a configuration-derived lookup is worth building once. Fourth, what does it depend on? A service can't live longer than anything it holds, so a 'stateless' service that takes aDbContextis scoped whether I like it or not.For the standard cases:
DbContextis scoped, whichAddDbContextdoes for you. It isn't thread-safe and its change tracker should die with the unit of work. If I need a context in a singleton or a long-running job, I injectIDbContextFactory<T>and create one per operation.HttpClientI get fromIHttpClientFactoryas a typed client; the factory pools handlers and rotates them every two minutes by default, which solves both socket exhaustion and stale DNS. If I can't use the factory, one static or singleton client withSocketsHttpHandler.PooledConnectionLifetimeset does the same.IMemoryCacheis a singleton; that's the point of it. A stateless domain service I usually register as transient or scoped to keep options open, and only make it a singleton if all its dependencies are singletons.The mistake I see is picking lifetimes for performance. Allocating a small transient costs nanoseconds; a singleton with a hidden scoped dependency costs an outage. I pick the narrowest lifetime that's correct, then widen it if a profiler tells me to."
| Question | If yes |
|---|---|
| Holds state for one request / message? | Scoped |
| Holds shared state, thread-safe? | Singleton |
| Expensive to construct, stateless, thread-safe? | Singleton |
| Stateless and cheap? | Transient (or scoped) |
| Depends on something scoped? | At most scoped |
| Must be a fresh object per consumer (builder, mutable helper)? | Transient |
| Service | Lifetime | Why |
|---|---|---|
DbContext |
Scoped | Not thread-safe; change tracker = one unit of work |
IDbContextFactory<T> |
Singleton | Creates short-lived contexts for workers, Blazor, parallel work |
Typed HttpClient (AddHttpClient<T>) |
Transient client, pooled handler | Factory rotates handlers (HandlerLifetime, default 2 min) |
Plain HttpClient |
Singleton with PooledConnectionLifetime |
Avoids socket exhaustion and stale DNS |
IMemoryCache, HybridCache |
Singleton | Thread-safe shared store |
IOptions<T> |
Singleton | IOptionsSnapshot<T> is scoped, IOptionsMonitor<T> singleton |
ILogger<T> |
Singleton | Thread-safe, cheap |
| Current user / tenant context | Scoped | Per request |
| Stateless domain service | Transient or scoped; singleton only if its graph is all singletons | Avoids hidden captive dependencies |
A pricing service registered a PriceCalculator as a singleton because it "had no state". It took an IPriceRepository, which took the scoped DbContext. In Production (scope validation off) every request shared one context; under [about 200] requests per second we saw InvalidOperationException: A second operation was started on this context at roughly [2%] of requests. Making the calculator scoped removed the errors with no measurable latency change.
Checks that the candidate chooses lifetimes from state, thread safety and dependencies, and knows the standard answers for DbContext, HttpClient and caches.
Green flags
DbContext is not thread-safe and mentions IDbContextFactory<T>IHttpClientFactory handler pooling, or PooledConnectionLifetime, and DNSRed flags
new HttpClient() per request, or a singleton DbContextThe effective lifetime of a service is the minimum of its own lifetime and those of everything below it that it holds:
PriceCalculator (singleton?)
└─ IPriceRepository (scoped)
└─ AppDbContext (scoped)
=> PriceCalculator must be scoped or transient
If you register it as a singleton anyway, the first scope that resolves it wins and every later request shares that scope's repository and context.
DbContext is not thread-safe: one connection, one change tracker, one ongoing operation. EF Core detects concurrent use and throws.DetectChanges.SaveChangesAsync.Outside requests use IDbContextFactory<T>:
singleton IDbContextFactory<AppDbContext>
└─ CreateDbContextAsync() per operation → await using
AddPooledDbContextFactory also reuses context instances (reset between uses), cutting allocation for high-throughput paths.
HttpClient is a thin wrapper; the SocketsHttpHandler owns the connection pool.
TIME_WAIT → exhaustion.Fixes: IHttpClientFactory pools handlers and recycles them after HandlerLifetime (2 minutes by default); or a long-lived handler with PooledConnectionLifetime (for example 2–5 minutes). Typed clients are registered transient; injecting one into a singleton captures its handler and loses the rotation.
MemoryCache uses concurrent structures internally and is meant to be shared, so it is a singleton. Your own singleton with a Dictionary<,> field is not safe; use ConcurrentDictionary or a lock, and watch for compound operations.
| Lifetime | Resolve cost (after first call) |
|---|---|
| Singleton | Cache lookup |
| Scoped | Per-scope dictionary lookup, first time builds |
| Transient | Construct every time (+ track if disposable) |
Differences are tens of nanoseconds; they matter only on extremely hot paths, and a benchmark should show it first.
ValidateScopes off and on and compare behaviour.Parallel.ForEachAsync over one DbContext and read the exception; repeat with IDbContextFactory<T>.dotnet-counters monitor System.Net.Http while creating a new HttpClient per request versus using a typed client.Registrations that follow the decision rules.
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Singleton IDbContextFactory<AppDbContext> for workers and parallel work.
// Since EF Core 6 this also registers AppDbContext itself as scoped,
// so request handlers can still inject the context directly.
builder.Services.AddDbContextFactory<AppDbContext>(o =>
o.UseSqlServer(builder.Configuration.GetConnectionString("App")));
// Typed client: transient client, pooled handler rotated every 2 minutes.
builder.Services.AddHttpClient<IRatesClient, RatesClient>(c =>
c.BaseAddress = new Uri("https://rates.example.com"));
// Thread-safe shared state.
builder.Services.AddMemoryCache();
// Depends on scoped repository → scoped, not singleton.
builder.Services.AddScoped<IPriceRepository, PriceRepository>();
builder.Services.AddScoped<PriceCalculator>();
// Pure, dependency-free, thread-safe → singleton is fine.
builder.Services.AddSingleton<IGstCalculator, GstCalculator>();
builder.Host.UseDefaultServiceProvider(o =>
{
o.ValidateScopes = true; // fail fast on captive dependencies in every environment
o.ValidateOnBuild = true;
});
var app = builder.Build();
app.Run();
public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options);
public interface IRatesClient;
public sealed class RatesClient(HttpClient http) : IRatesClient;
public interface IPriceRepository;
public sealed class PriceRepository(AppDbContext db) : IPriceRepository;
public sealed class PriceCalculator(IPriceRepository repo, IGstCalculator gst);
public interface IGstCalculator { decimal AddGst(decimal amount); }
public sealed class GstCalculator : IGstCalculator { public decimal AddGst(decimal amount) => amount * 1.10m; }
If you cannot use IHttpClientFactory:
namespace Rates;
public static class SharedHttp
{
// One handler for the process, but connections are recycled so DNS changes are picked up.
public static readonly HttpClient Client = new(new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(2)
});
}
ValidateScopes everywhere.DbContext as a singleton to "avoid reconnecting". Why it is wrong: Connection pooling already makes opening cheap; a shared context is not thread-safe and its change tracker grows without bound. Instead: Scoped, or IDbContextFactory<T> per operation.new HttpClient() per call inside a transient service. Why it is wrong: Each instance owns a handler and connections, causing socket exhaustion under load. Instead: IHttpClientFactory or a long-lived handler with PooledConnectionLifetime.HttpClient into a singleton. Why it is wrong: The singleton keeps one handler for ever, so handler rotation and DNS refresh are lost. Instead: Make the consumer transient/scoped, or inject IHttpClientFactory and call CreateClient per use.Dictionary or List. Why it is wrong: Concurrent requests corrupt it. Instead: Immutable data, concurrent collections or proper locking.Choosing a lifetime is really choosing a concurrency model and an ownership model at the same time. A singleton promises "many threads, for ever"; a scoped service promises "one unit of work, then gone". I default to the narrowest correct lifetime and widen only with evidence, because the failure modes are asymmetric: an unnecessary transient costs a few nanoseconds and a small Gen0 allocation, an incorrect singleton corrupts data under load and often only shows up in production, where scope validation is off by default.
Pooling is how you get performance without widening the lifetime: AddDbContextPool keeps the per-request contract but reuses context instances (EF resets them between leases), and IHttpClientFactory pools handlers while handing out cheap transient clients. That is the senior move: keep the semantic lifetime correct and optimise the expensive part underneath.
| Choice | When it fits | Cost | When not to |
|---|---|---|---|
AddDbContext (scoped) |
Request-based apps | One context allocation per request | Background loops, Blazor Server components with long circuits |
AddDbContextPool |
Hot request paths where context construction shows in profiles | Context must not hold per-request state in fields; pool size default 1024 | Contexts with injected scoped services or custom state |
IDbContextFactory<T> |
Workers, parallel work, Blazor | You own disposal | Simple request handlers (adds ceremony) |
IHttpClientFactory typed client |
Most outbound HTTP | Small registration overhead | Consumer is a singleton (captures handler) |
Singleton HttpClient + PooledConnectionLifetime |
Libraries, console apps, singletons | No named config or handler pipeline | You need per-client resilience handlers via the factory |
To verify a choice I look at the dependency graph (with ValidateOnBuild), run a quick concurrent load test against the endpoint, and watch for EF concurrency exceptions, allocation rate (dotnet-counters, gc-heap-size and alloc-rate) and memory growth in Application Insights.
Two different limits produce similar errors:
EMFILE, "Too many open files"): the process hit its ulimit -n. Something is leaking files or sockets.EADDRNOTAVAIL, "Cannot assign requested address"): too many outbound connections to the same destination, usually closed sockets stuck in TIME_WAIT for 60 s.The classic .NET cause is new HttpClient() per request. Fix it with a shared HttpClient using SocketsHttpHandler { PooledConnectionLifetime = ... }, or IHttpClientFactory. Diagnose with ls /proc/<pid>/fd | wc -l, lsof -p, ss -s and ss -tan state time-wait.
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>.
When the container can't build something up front, inject a factory instead of the object.
AddScoped<IFoo>(sp => ...)) runs logic at resolution time, for example choosing an implementation from configuration.Func<T> or Lazy<T>; you register them explicitly.ActivatorUtilities.CreateFactory (the generic ObjectFactory<T> overload arrived in .NET 8), which mixes your argument with container services and caches the reflection.The key rule: anything a factory creates is owned by the caller, who must dispose it. The trade-off is flexibility against hidden lifetimes: factories are the main way captive and leaked dependencies sneak in.
Last updated 23 Nov 2026.