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

📚 Interview question

Code review: a Program.cs registers AppDbContext with AddSingleton, a TenantMiddleware takes the scoped ITenantContext in its constructor, a singleton ReportScheduler resolves a transient IDisposable exporter from an injected IServiceProvider on every run, and an HttpClient is registered as AddSingleton(new HttpClient()). What problems do you see, ranked by severity, and how would you fix them?

Covers reviewing DI registrations for lifetime defects: a singleton DbContext, a scoped service in a conventional middleware constructor, root-tracked transient disposables in a singleton, and a singleton HttpClient that never sees DNS changes, with the rewrite and review guard rails.

Senior CodeReview Advanced code-review dbcontext dependency-injection httpclient middleware service-lifetimes

🎯 Key points

  • Conventional middleware is constructed once (singleton): a scoped ITenantContext in its constructor is captive, so one tenant's context is used for every request (cross-tenant data exposure)
  • Fix middleware: inject scoped services as InvokeAsync parameters, or implement IMiddleware registered as scoped
  • Singleton DbContext: one non-thread-safe instance shared by concurrent requests, so concurrency exceptions, stale identity-map data, other requests' pending changes committed, and a change tracker that keeps growing
  • Transient IDisposable resolved from the root provider in a singleton: tracked until shutdown, memory leak
  • ValidateScopes/ValidateOnBuild catch captive scoped dependencies only; they say nothing about root-tracked transients or HttpClient connection lifetime
  • AddSingleton(new HttpClient()): reusing one handler is right for sockets, but default PooledConnectionLifetime is infinite so connections never re-resolve DNS; the container also won't dispose it
  • Fix HttpClient: AddHttpClient typed client (handler rotation, default 2 min) or SocketsHttpHandler with PooledConnectionLifetime
  • Guard rails: validation in every environment, host-build test, concurrent multi-tenant test, analyser bans, registration checklist

⏱ 30-second answer

Four lifetime defects, worst first:

  1. Scoped ITenantContext in TenantMiddleware's constructor: conventional middleware is built once, so the first request's tenant context is reused for every request. That is a cross-tenant data exposure (and a possible notifiable data breach). Inject it into InvokeAsync instead, or use IMiddleware.
  2. Singleton AppDbContext: one context for all threads: "second operation" exceptions, stale data, growing change tracker. Use AddDbContext (scoped) or IDbContextFactory<T>.
  3. Transient disposable resolved from the root in a singleton: the root tracks every exporter until shutdown, a slow memory leak. Use a factory with using, or a scope per run.
  4. AddSingleton(new HttpClient()): connections are never recycled, so DNS changes are missed after failover. Use AddHttpClient or PooledConnectionLifetime.

Then turn on ValidateScopes/ValidateOnBuild everywhere; they would have caught 1 and 2, not 3 or 4.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd read registrations as a set of ownership and concurrency promises, then check each against how the type is used. The worst issue here isn't the one that crashes, it's the middleware. Conventional middleware is constructed once when the pipeline is built, so anything in its constructor is effectively a singleton. ITenantContext is scoped and holds the current tenant, so after the first request every request runs with that first tenant's context. That's a cross-tenant data exposure, which for us would be [a potential eligible data breach under the Notifiable Data Breaches scheme]. The fix is to take ITenantContext as a parameter of InvokeAsync, which is resolved per request, or implement IMiddleware and register it as scoped.

Second, the singleton DbContext: every request shares one connection and one change tracker, so you get 'A second operation was started' under load, stale data from the identity map and memory growth. AddDbContext gives you scoped; anything that needs a context outside a request gets IDbContextFactory<T>. Third, the scheduler is a singleton holding the root IServiceProvider, resolving a transient IDisposable exporter every run. The root tracks each one until shutdown, so that's a leak that scope validation won't flag. I'd inject a factory and dispose with using, or create a scope per run. Fourth, new HttpClient() as a singleton avoids socket exhaustion but keeps connections for ever, so after a DNS failover we keep calling the old address. AddHttpClient or PooledConnectionLifetime fixes it.

For example, at [company] we [found the middleware issue in review before it shipped; a similar bug elsewhere had shown one customer another's dashboard for about 20 minutes]. My closing comment would be to enable ValidateScopes and ValidateOnBuild in every environment, because issues one and two then fail at start-up instead of in production."


Code under review

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<AppDbContext>();                      // 2
builder.Services.AddScoped<ITenantContext, TenantContext>();
builder.Services.AddTransient<IReportExporter, ExcelExporter>();    // ExcelExporter : IDisposable
builder.Services.AddSingleton<ReportScheduler>();                   // 3
builder.Services.AddSingleton(new HttpClient                        // 4
{
    BaseAddress = new Uri("https://rates.example.com")
});

var app = builder.Build();
app.UseMiddleware<TenantMiddleware>();
app.Run();

public sealed class TenantMiddleware(RequestDelegate next, ITenantContext tenant) // 1
{
    public async Task InvokeAsync(HttpContext context)
    {
        tenant.TenantId = context.Request.Headers["X-Tenant"].ToString();
        await next(context);
    }
}

public sealed class ReportScheduler(IServiceProvider services)
{
    public async Task RunAsync(CancellationToken ct)
    {
        var exporter = services.GetRequiredService<IReportExporter>(); // 3: root-tracked
        await exporter.ExportAsync(ct);
    }
}

Findings, by severity

# Severity Finding Effect
1 Security Scoped ITenantContext captured by singleton-lifetime middleware Requests share one tenant context: cross-tenant reads and writes
2 Crash / wrong data AddSingleton<AppDbContext> Concurrency exceptions, stale data, unbounded memory
3 Resource leak Transient IDisposable resolved from root in a singleton Every exporter kept until shutdown; not caught by validation
4 Availability Singleton HttpClient with default handler No connection recycling, stale DNS after failover; never disposed by container
5 Design ReportScheduler depends on IServiceProvider Hidden dependency; service locator

The rewrite

using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// 2: scoped context for requests + singleton factory for background work.
builder.Services.AddDbContextFactory<AppDbContext>(o =>
    o.UseSqlServer(builder.Configuration.GetConnectionString("App")));

builder.Services.AddScoped<ITenantContext, TenantContext>();

// 3: the scheduler owns per-run exporters explicitly.
builder.Services.AddSingleton<Func<IReportExporter>>(() => new ExcelExporter());
builder.Services.AddSingleton<ReportScheduler>();

// 4: pooled, rotated handlers.
builder.Services.AddHttpClient<IRatesClient, RatesClient>(c =>
    c.BaseAddress = new Uri("https://rates.example.com"));

builder.Host.UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; });

var app = builder.Build();
app.UseMiddleware<TenantMiddleware>();
app.Run();

// 1: scoped dependency moved to InvokeAsync, resolved per request.
public sealed class TenantMiddleware(RequestDelegate next)
{
    public async Task InvokeAsync(HttpContext context, ITenantContext tenant)
    {
        tenant.TenantId = context.Request.Headers["X-Tenant"].ToString();
        await next(context);
    }
}

public sealed class ReportScheduler(Func<IReportExporter> createExporter)
{
    public async Task RunAsync(CancellationToken ct)
    {
        using var exporter = createExporter(); // owned and disposed per run
        await exporter.ExportAsync(ct);
    }
}

How I'd close the review

Comment Type
Middleware tenant capture (1) Blocking: security defect
Singleton DbContext (2) Blocking
Root-tracked exporters (3) Blocking: leak
HttpClient registration (4) Blocking for a production service; link the DNS failover runbook
Enable both validations everywhere + host-build test Suggested, strongly
Add a registration checklist to the PR template (lifetime, thread safety, disposal, consumers) Suggested

Production example

In a [multi-tenant SaaS on Azure Australia East], the same middleware pattern caused [one tenant's users to see another's records for ~20 minutes after a deploy]. After moving the dependency to InvokeAsync, turning on validation everywhere and adding a test that sends interleaved requests for two tenants, [no cross-tenant incident has recurred in 12 months].

🔍 What the interviewer is checking

Checks that the candidate can spot lifetime defects in registration code, rank them by real impact (security first), and fix each with the correct pattern.

Green flags

  • Knows conventional middleware is a singleton and moves scoped deps to InvokeAsync or IMiddleware
  • Treats the tenant leak as a security defect, ranked first
  • Explains root-tracked transients and that validation misses them
  • Explains HttpClient DNS staleness and PooledConnectionLifetime / IHttpClientFactory
  • Closes with validation everywhere and tests

Red flags

  • Ranks the HttpClient style issue above the tenant leak
  • Thinks AddSingleton(new HttpClient()) is fully correct
  • Fixes the DbContext with a lock

📚 Learn in depth

1. Middleware lifetimes

Conventional middleware (a class with InvokeAsync) is activated once by UseMiddleware<T>() with ActivatorUtilities, from the application (root) services:

Pipeline build (once)
  TenantMiddleware(next, ITenantContext ← resolved from ROOT)   ← captive
Per request
  InvokeAsync(context, <extra params resolved from context.RequestServices>)

Constructor parameters: singleton semantics. InvokeAsync parameters after HttpContext: resolved from the request scope every call. With ValidateScopes on, the constructor version throws Cannot resolve scoped service 'ITenantContext' from root provider at pipeline build.

Factory-based middleware (IMiddleware) is resolved from the request scope per request via IMiddlewareFactory, so it can be registered as scoped or transient and take scoped constructor dependencies.

2. Singleton DbContext

Request A ─┐
Request B ─┼─► AppDbContext (single) ─► one connection, one StateManager
Request C ─┘

EF's concurrency detector throws on overlap; non-overlapping requests see each other's tracked entities and pending changes. A SaveChanges in request A can commit request B's half-made changes.

3. Root-tracked transients

The singleton receives the root IServiceProvider. Each GetRequiredService<IReportExporter>() builds a new ExcelExporter and, because it is IDisposable, adds it to the root scope's disposables list. Nothing removes it until shutdown. Neither validation option detects this.

4. HttpClient and DNS

new HttpClient() creates a SocketsHttpHandler with PooledConnectionLifetime = InfiniteTimeSpan. A pooled connection is reused while it stays healthy, so DNS is resolved only when a new connection opens. After a DNS failover (for example Azure Traffic Manager or Front Door switching regions), healthy connections keep pointing at the old IP. Fixes:

  • AddHttpClient: IHttpClientFactory rotates handlers every HandlerLifetime (2 minutes by default).
  • Or new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(2) } in a long-lived client.

Also, AddSingleton(instance) means the container never disposes the client.

5. What validation would have caught

Finding ValidateScopes ValidateOnBuild
1 Middleware capture Yes, when the pipeline is built No (middleware isn't a registered service)
2 Singleton DbContext No direct error (its own lifetime is singleton), but its scoped DbContextOptions dependency fails Yes, same reason
3 Root transients No No
4 HttpClient No No

So validation is necessary, not sufficient: 3 and 4 need review knowledge.

Try it yourself

  1. Reproduce finding 1 with ValidateScopes off; send interleaved requests with two X-Tenant headers and log the tenant inside a handler.
  2. Turn validation on and read the start-up error.
  3. Register the singleton DbContext and run a 50-user k6 test; count exceptions.
  4. Point a singleton HttpClient at a hostname, change the hosts-file entry while it runs, and observe it keep using the old IP; repeat with PooledConnectionLifetime = 30s.

💻 Code

The types the rewrite relies on: the exporter abstraction must itself be disposable for using to work.

namespace Reports;

public interface IReportExporter : IDisposable
{
    Task ExportAsync(CancellationToken ct);
}

public sealed class ExcelExporter : IReportExporter
{
    public Task ExportAsync(CancellationToken ct) => Task.CompletedTask;
    public void Dispose() { /* release workbook / file handles */ }
}

The factory-based middleware alternative, and a test that would catch tenant leakage.

namespace Tenancy;

public interface ITenantContext { string? TenantId { get; set; } }
public sealed class TenantContext : ITenantContext { public string? TenantId { get; set; } }

// IMiddleware is resolved per request from the request scope, so scoped constructor deps are fine.
public sealed class TenantMiddleware(ITenantContext tenant) : IMiddleware
{
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        tenant.TenantId = context.Request.Headers["X-Tenant"].ToString();
        await next(context);
    }
}
// Program.cs
builder.Services.AddScoped<Tenancy.ITenantContext, Tenancy.TenantContext>();
builder.Services.AddScoped<Tenancy.TenantMiddleware>(); // must be registered for IMiddleware

var app = builder.Build();
app.UseMiddleware<Tenancy.TenantMiddleware>();
app.MapGet("/whoami", (Tenancy.ITenantContext t) => t.TenantId);
app.Run();

public partial class Program;
using Microsoft.AspNetCore.Mvc.Testing;

namespace Tenancy.Tests;

public sealed class TenantIsolationTests(WebApplicationFactory<Program> factory)
    : IClassFixture<WebApplicationFactory<Program>>
{
    [Fact]
    public async Task Interleaved_requests_keep_their_own_tenant()
    {
        var client = factory.CreateClient();
        var tasks = Enumerable.Range(0, 200).Select(async i =>
        {
            var expected = i % 2 == 0 ? "acme" : "globex";
            using var req = new HttpRequestMessage(HttpMethod.Get, "/whoami");
            req.Headers.Add("X-Tenant", expected);
            var actual = await (await client.SendAsync(req)).Content.ReadAsStringAsync();
            return (expected, actual);
        });

        foreach (var (expected, actual) in await Task.WhenAll(tasks))
            Assert.Equal(expected, actual);
    }
}
// If IHttpClientFactory is not an option (e.g. a library), keep one handler but recycle connections.
namespace Rates;

public static class RatesHttp
{
    public static HttpClient Create() => new(new SocketsHttpHandler
    {
        PooledConnectionLifetime = TimeSpan.FromMinutes(2), // re-resolve DNS at least every 2 minutes
        PooledConnectionIdleTimeout = TimeSpan.FromMinutes(1)
    })
    {
        BaseAddress = new Uri("https://rates.example.com")
    };
}

⚠ Common mistakes

  • Mistake: Putting scoped services in a conventional middleware constructor. Why it is wrong: The middleware is built once, so the scoped instance is shared by every request; with per-request identity this leaks data between users or tenants. Instead: InvokeAsync parameters, or IMiddleware registered as scoped.
  • Mistake: AddSingleton<AppDbContext>() (or registering the context manually as a singleton). Why it is wrong: Not thread-safe; shared change tracker and stale data. Instead: AddDbContext / AddDbContextFactory.
  • Mistake: Resolving transients from an injected IServiceProvider inside a singleton. Why it is wrong: That provider is the root; disposables are tracked until shutdown. Instead: Func<T>/typed factory with using, or IServiceScopeFactory per run.
  • Mistake: Treating AddSingleton(new HttpClient()) as the fix for socket exhaustion. Why it is wrong: It trades exhaustion for stale DNS and the container never disposes it. Instead: AddHttpClient or PooledConnectionLifetime.
  • Mistake: Approving because the app starts and tests pass. Why it is wrong: Default validation runs only in Development, and single-user tests never overlap requests. Instead: Validation everywhere, plus a concurrent multi-tenant test.
  • Mistake: Ranking findings by how easy they are to fix. Why it is wrong: The security defect gets buried under cosmetic comments. Instead: Rank by impact: security and data corruption first.

🏛 Senior insight: trade-offs

Registration code looks boring, so it gets rubber-stamped, yet it encodes the concurrency and ownership model of the whole app. I review it with four questions per line: who shares this instance, is it thread-safe, who disposes it, and what does it depend on? Then I check who consumes it, because middleware and hosted services are singletons regardless of how their dependencies are registered.

Guard rail Catches Cost Misses
ValidateScopes + ValidateOnBuild everywhere Captive scoped deps, missing registrations Milliseconds at start-up Root-tracked transients, HttpClient DNS, factory delegates
Host-build integration test (Production environment) Same, in CI Seconds per run Same
Concurrent multi-tenant test Per-request identity leaks A minute to write Non-HTTP flows
BannedApiAnalyzers (IServiceProvider outside composition, new HttpClient) Locator and client misuse Initial suppressions Creative workarounds
PR checklist for registration changes Human judgement on lifetimes Reviewer time Rushed reviews

I'd measure success by zero lifetime-related incidents and by the validation failures that show up in CI instead of production.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate identifies the singleton DbContext Why: Checks they can diagnose the captive dependency from production symptoms
    How to answer

    It is a captive dependency. The singleton was built once, from the first request's scope, so it holds that request's DbContext for ever. Every user now shares one context: its identity map returns stale entities that were tracked earlier, concurrent requests hit it at the same time and EF throws "A second operation was started", and the change tracker grows. Often the first scope's disposal even leaves it disposed (ObjectDisposedException).

    Development would have thrown, because ValidateScopes is on only in Development by default. I confirm by enabling ValidateScopes and ValidateOnBuild and reading the exception. The fix is to make PricingService scoped, or, if it truly must be a singleton (it holds a cache), inject IDbContextFactory<AppDbContext> and create a context per operation. Then turn validation on everywhere.

  2. When: Candidate mentions the root provider tracking the exporters Why: Checks how they'd find that leak in a running system
    How to answer

    First I confirm it is the managed heap: dotnet-counters shows gc-heap-size and Gen2 climbing even after full collections. Then I take two dotnet-gcdumps an hour apart, diff the type counts, and follow the retention path of the growing type.

    If the path runs through ServiceProviderEngineScope → disposables, the container is holding them. Three usual causes:

    • Transient IDisposables resolved from the root (static helpers, singletons using an injected IServiceProvider): tracked until shutdown.
    • Scopes that live too long: one scope for a worker's whole loop, never-disposed scopes, long Blazor circuits.
    • Singletons that accumulate: a captive DbContext change tracker, unbounded dictionaries, unremoved event handlers.

    Fix by resolving inside short scopes, owning per-call disposables through factories and using, and bounding caches. ValidateScopes doesn't catch root-tracked transients, so add a soak test and a working-set alert.

  3. When: Candidate mentions stale DNS with HttpClient Why: Checks DNS behaviour and diagnosis in cloud environments
    How to answer

    DNS maps names to records: A (IPv4), AAAA (IPv6), CNAME (alias), plus MX, TXT, SRV, NS and PTR. A client asks a recursive resolver, which walks root → TLD → authoritative servers and caches the answer for its TTL. .NET uses the OS resolver (getaddrinfo) and does not cache itself.

    Typical incidents:

    • Stale endpoint after failover: DNS changed, but HttpClient kept pooled connections to the old IP. Fix with PooledConnectionLifetime.
    • Slow or failing lookups in Kubernetes: ndots:5 makes each external name try several search domains first, and UDP conntrack races cause occasional 5-second delays.
    • Split-horizon / private endpoints: the name resolves to a public IP from one network and a private IP from another.

    Diagnose with dig/nslookup from the same pod, check TTLs, and look at the DNS phase of the HTTP timing.

🛠 Real-world problems: how you handle them

Middleware captured the scoped tenant context and leaked data across tenants
Situation
[Multi-tenant B2B SaaS on Azure App Service, Australia East, ~150 tenants]. A refactor moved tenant resolution into TenantMiddleware and injected the scoped ITenantContext into its constructor. All environments ran with ASPNETCORE_ENVIRONMENT=Production-like names, so scope validation was off.
Signals
A customer support ticket: a user saw another company's invoices after a deploy. Audit logs showed requests carrying tenant A's header but querying tenant B's data for [~20 minutes] until an unrelated restart.
Investigation
Correlated audit log entries by request id and saw the tenant id in queries didn't match the header. Reviewed the deploy diff and found the constructor injection. Reproduced locally with ValidateScopes off using interleaved requests for two tenants; with validation on, pipeline build failed with 'Cannot resolve scoped service ITenantContext from root provider'.
Resolution
Immediate: rolled back the release and restarted all instances. Real fix: ITenantContext moved to an InvokeAsync parameter; EF global query filters keyed on the tenant id as defence in depth. Ran the Notifiable Data Breaches assessment with the privacy officer and notified the affected tenants.
Prevention
ValidateScopes and ValidateOnBuild enabled in every environment; a concurrent two-tenant integration test in CI; PR checklist item for middleware and hosted-service constructors; alert on audit entries where header tenant and data tenant differ.

How to tell it (STAR)

**S:** At [company], after a deploy of our multi-tenant platform, [a customer reported seeing another company's invoices]. **T:** I [led the technical investigation] and needed to stop the exposure, find the cause and make sure it couldn't recur. **A:** Audit logs showed requests with one tenant's header reading another tenant's data. The diff showed the scoped tenant context injected into a middleware constructor; middleware is built once, so every request shared the first tenant's context. We rolled back immediately, moved the dependency to InvokeAsync, added tenant query filters as a second line of defence, and turned on scope validation in every environment with a concurrent two-tenant test. I also [worked with our privacy officer on the breach assessment and customer notifications]. **R:** Exposure was limited to [about 20 minutes and N tenants], and in the [12 months] since, validation has failed [two] similar changes in CI before they could ship.

More in Service Lifetimes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me