📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you decide which lifetime to give a service? Walk through the questions you ask (state, thread safety, cost, dependencies), and say which lifetime you would choose for a DbContext, an HttpClient, an in-memory cache and a stateless domain service, and why.

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.

Intermediate Theory Intermediate caching dbcontext dependency-injection httpclient service-lifetimes thread-safety

🎯 Key points

  • Ask: does it hold state, is that state per unit of work or shared, is it thread-safe, what does it depend on
  • DbContext: scoped (AddDbContext default); not thread-safe, one unit of work, change tracker grows
  • High throughput: AddDbContextPool reuses scoped instances (reset between requests) without changing the per-request contract
  • DbContext in singletons or long work: IDbContextFactory<T> (AddDbContextFactory / AddPooledDbContextFactory), a context per operation
  • HttpClient: IHttpClientFactory (singleton factory, transient typed/named clients, handlers rotated every 2 min by default) or one long-lived client with SocketsHttpHandler.PooledConnectionLifetime
  • IMemoryCache / HybridCache: singleton, thread-safe by design
  • Stateless service: transient or singleton both work; singleton only if all its dependencies are singletons
  • A service can never live longer than its shortest-lived dependency

⏱ 30-second answer

I choose by state and thread safety, then check dependencies:

  1. Does it hold per-unit-of-work state (a change tracker, the current user)? → scoped.
  2. Is it shared, thread-safe and worth building once (a cache, a client pool, compiled config)? → singleton.
  3. Stateless and cheap? → transient (or singleton if every dependency is a singleton).
  4. A service can't outlive its shortest-lived dependency.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 IHttpClientFactory is 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 a DbContext is scoped whether I like it or not.

For the standard cases: DbContext is scoped, which AddDbContext does 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 inject IDbContextFactory<T> and create one per operation. HttpClient I get from IHttpClientFactory as 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 with SocketsHttpHandler.PooledConnectionLifetime set does the same. IMemoryCache is 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."


The decision questions

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

Standard choices

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate chooses lifetimes from state, thread safety and dependencies, and knows the standard answers for DbContext, HttpClient and caches.

Green flags

  • States the shortest-lived-dependency rule
  • Knows DbContext is not thread-safe and mentions IDbContextFactory<T>
  • Explains IHttpClientFactory handler pooling, or PooledConnectionLifetime, and DNS
  • Prefers the narrowest correct lifetime

Red flags

  • "Singleton everything for performance"
  • new HttpClient() per request, or a singleton DbContext
  • Ignores thread safety of shared state

📚 Learn in depth

1. Lifetimes are a property of the whole graph

The 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.

2. Why DbContext is scoped

  • DbContext is not thread-safe: one connection, one change tracker, one ongoing operation. EF Core detects concurrent use and throws.
  • The change tracker grows with every tracked entity; keeping a context for the life of the process means memory growth and slower DetectChanges.
  • A request is a natural unit of work: load, change, 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.

3. HttpClient: the instance is cheap, the handler is not

HttpClient is a thin wrapper; the SocketsHttpHandler owns the connection pool.

  • New handler per request → new connections each time → sockets in TIME_WAIT → exhaustion.
  • One handler for ever → connections never re-resolve DNS → traffic stuck on old IPs after a failover.

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.

4. Caches and thread safety

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.

5. Cost of each lifetime

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.

Try it yourself

  1. Register a singleton that depends on a scoped service; run with ValidateScopes off and on and compare behaviour.
  2. Use Parallel.ForEachAsync over one DbContext and read the exception; repeat with IDbContextFactory<T>.
  3. BenchmarkDotNet: resolve a singleton, scoped and transient service 1 million times each and compare.
  4. Watch dotnet-counters monitor System.Net.Http while creating a new HttpClient per request versus using a typed client.

💻 Code

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)
    });
}

⚠ Common mistakes

  • Mistake: Registering a "stateless" service as a singleton without checking its dependencies. Why it is wrong: If anything below it is scoped, it captures one request's instances for ever. Instead: Check the whole graph, and turn on ValidateScopes everywhere.
  • Mistake: Registering 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.
  • Mistake: 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.
  • Mistake: Injecting a typed 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.
  • Mistake: Choosing transient for everything to be "safe". Why it is wrong: Expensive objects get rebuilt per resolve, and disposable transients pile up in long-lived scopes. Instead: Pick by state; transient is a choice, not a default.
  • Mistake: Keeping mutable state in a singleton with a plain Dictionary or List. Why it is wrong: Concurrent requests corrupt it. Instead: Immutable data, concurrent collections or proper locking.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions socket exhaustion or creating HttpClient per request Why: Checks they can diagnose the production symptom behind the HttpClient lifetime rules
    How to answer

    Two different limits produce similar errors:

    1. Descriptor exhaustion (EMFILE, "Too many open files"): the process hit its ulimit -n. Something is leaking files or sockets.
    2. Ephemeral port exhaustion (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.

  2. When: Candidate says singletons must be thread-safe Why: Checks how they would make shared singleton state safe
    How to answer

    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>.

  3. When: Candidate mentions IDbContextFactory or creating instances per operation Why: Checks factory injection patterns for run-time instances
    How to answer

    When the container can't build something up front, inject a factory instead of the object.

    • A factory registration (AddScoped<IFoo>(sp => ...)) runs logic at resolution time, for example choosing an implementation from configuration.
    • Unlike Autofac, the built-in container (still true in .NET 10) does not auto-supply Func<T> or Lazy<T>; you register them explicitly.
    • For run-time values, define a small typed factory interface and implement it with 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.

↩ Usually asked after

More in Service Lifetimes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me