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.
Four lifetime defects, worst first:
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.AppDbContext: one context for all threads: "second operation" exceptions, stale data, growing change tracker. Use AddDbContext (scoped) or IDbContextFactory<T>.using, or a scope per run.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.
"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.
ITenantContextis 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 takeITenantContextas a parameter ofInvokeAsync, which is resolved per request, or implementIMiddlewareand 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.AddDbContextgives you scoped; anything that needs a context outside a request getsIDbContextFactory<T>. Third, the scheduler is a singleton holding the rootIServiceProvider, resolving a transientIDisposableexporter 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 withusing, 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.AddHttpClientorPooledConnectionLifetimefixes 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
ValidateScopesandValidateOnBuildin every environment, because issues one and two then fail at start-up instead of in production."
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);
}
}
| # | 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 |
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);
}
}
| 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 |
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].
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
InvokeAsync or IMiddlewareHttpClient DNS staleness and PooledConnectionLifetime / IHttpClientFactoryRed flags
HttpClient style issue above the tenant leakAddSingleton(new HttpClient()) is fully correctDbContext with a lockConventional 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.
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.
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.
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).new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(2) } in a long-lived client.Also, AddSingleton(instance) means the container never disposes the client.
| 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.
ValidateScopes off; send interleaved requests with two X-Tenant headers and log the tenant inside a handler.DbContext and run a 50-user k6 test; count exceptions.HttpClient at a hostname, change the hosts-file entry while it runs, and observe it keep using the old IP; repeat with PooledConnectionLifetime = 30s.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")
};
}
InvokeAsync parameters, or IMiddleware registered as scoped.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.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.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.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.
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.
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:
IDisposables resolved from the root (static helpers, singletons using an injected IServiceProvider): tracked until shutdown.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.
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:
HttpClient kept pooled connections to the old IP. Fix with PooledConnectionLifetime.ndots:5 makes each external name try several search domains first, and UDP conntrack races cause occasional 5-second delays.Diagnose with dig/nslookup from the same pod, check TTLs, and look at the DNS phase of the HTTP timing.
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.
Last updated 23 Nov 2026.