Code review of creational anti-patterns: racy static singleton, unsynchronised Dictionary, HttpClient per call, DbContext held by a singleton, sync-over-async, switch factory with silent fallback and hard-coded secret; rewrite with DI lifetimes, typed HttpClient, HybridCache, keyed or options-driven provider selection.
I'd rank the findings by production impact:
.Result blocks thread-pool threads (starvation). new HttpClient() per call exhausts sockets. A singleton holding a DbContext shares a non-thread-safe context across requests. A plain Dictionary written concurrently can corrupt itself and spin at 100% CPU.switch silently falls back to a default provider.Instance hides every dependency, and a switch factory edits the class for each new provider.In the rewrite the service is registered with DI. It gets a typed HttpClient with a resilience handler, HybridCache with expiry, a provider chosen once at startup from validated options, an audit writer using IDbContextFactory, async all the way with a CancellationToken, and the secret in Key Vault.
"I'd go through this by impact, not line by line. First, the things that will stall or crash the service under load.
Convertcalls.Resulton an async method, so every call blocks a thread-pool thread while it waits for HTTP, and at a few hundred requests per second that's thread-pool starvation. Every cache miss creates a newHttpClient, and each one opens a new connection whose socket sits inTIME_WAITafter disposal, so you run out of ports. The singleton owns aDbContext, which isn't thread-safe, so concurrent requests get 'A second operation was started on this context instance', and its change tracker grows forever. The cache is a plainDictionarywritten from many threads, which can corrupt its buckets and leave threads spinning at 100% CPU. Second, wrong data: the rates never expire, and theswitchhas a default branch, so a typo in config silently uses a different provider. Third, there's a hard-coded API key, which is a secret in source control.Then design. The static
Instanceis racy (??=isn't atomic) and hides every dependency, and theswitchmeans every new provider edits this class. For example, at [company] we had [a rates service like this] that took [the checkout] down at [month-end]. A dump showed [~200] threads blocked in.Resultand [the Dictionary spinning]. I rewrote it the way I'd suggest here, and [p99 went from timeouts to ~40 ms, with zero incidents in the following year].The rewrite is an
ICurrencyConverterregistered with DI. It's async with aCancellationToken, and it usesHybridCachewith a 15-minute expiry plus stampede protection. Each provider is a typedHttpClientwithAddStandardResilienceHandler, chosen once at startup from validated options, with the key in Key Vault. Audits go throughIDbContextFactory. Every creational problem here, from singleton and factory to client and context, is something the container already does better."
public class CurrencyService
{
private static CurrencyService? _instance;
public static CurrencyService Instance => _instance ??= new CurrencyService(); // 1
private readonly Dictionary<string, decimal> _rates = new(); // 2
private readonly AppDbContext _db = new AppDbContext(); // 3
public decimal Convert(decimal amount, string from, string to)
{
var rate = GetRateAsync(from, to).Result; // 4
return amount * rate;
}
private async Task<decimal> GetRateAsync(string from, string to)
{
if (_rates.TryGetValue(from + to, out var cached)) return cached; // 5
using var client = new HttpClient(); // 6
IRateProvider provider = CreateProvider(AppConfig.RateProvider);
decimal rate = await provider.GetRateAsync(client, from, to);
_rates[from + to] = rate; // 2, 5
_db.RateAudits.Add(new RateAudit(from, to, rate, DateTime.Now)); // 3, 9
await _db.SaveChangesAsync();
return rate;
}
private IRateProvider CreateProvider(string name) => name switch // 7
{
"xe" => new XeProvider("sk_live_9f2c..."), // 8
"rba" => new RbaProvider(),
_ => new XeProvider("sk_live_9f2c...") // 7
};
}
(4) .Result on async I/O. It blocks a thread-pool thread for the whole HTTP and database round trip. The pool injects threads slowly once it believes it's starved, so latency climbs across the whole service, not just this endpoint. It also wraps failures in AggregateException.
(6) new HttpClient() per call. Each client owns a handler and a connection pool; disposing it closes the connection, leaving the socket in TIME_WAIT for up to 240 seconds on Windows. Under load you get SocketException: Only one usage of each socket address⦠or "Too many open files" on Linux. No timeout is set, so the default 100 seconds applies.
(3) A DbContext owned by a singleton. It's created once and shared by every request. EF Core throws on concurrent use, and the change tracker keeps every RateAudit ever added in memory.
(2) Plain Dictionary with concurrent writes. Dictionary<TKey,TValue> isn't thread-safe for writes. Concurrent inserts during a resize can corrupt the bucket chains, and readers can then loop forever at 100% CPU.
(5) Cache never expires. Rates move during the day; the service returns the first rate it ever saw until restart. There's also no stampede protection: 500 concurrent misses make 500 provider calls.
(7) Silent default provider. A typo such as "RBA" falls through to Xe without a warning, giving different rates and different costs. The switch also violates Open/Closed.
(8) Hard-coded live API key. It's in source control, build artefacts and every developer's clone. Rotate it now, move it to Key Vault-backed configuration and enable secret scanning in CI.
(9) DateTime.Now and no logging. Local time on the server makes audits ambiguous across regions and daylight saving; no logging or metrics means provider failures are invisible. Use TimeProvider and structured logs.
(1) Static Instance with ??=. ??= is not atomic, so two threads can create two instances (and two DbContexts). More importantly, it hides HttpClient, DbContext, configuration and the provider choice, so nothing is testable or configurable.
namespace Currency;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.Options;
public interface IRateProvider
{
Task<decimal> GetRateAsync(string from, string to, CancellationToken ct);
}
public sealed class XeRateProvider(HttpClient http) : IRateProvider // typed client: base address, key header, resilience set in Program.cs
{
public async Task<decimal> GetRateAsync(string from, string to, CancellationToken ct)
{
RateResponse? r = await http.GetFromJsonAsync<RateResponse>($"/v1/convert?from={from}&to={to}", ct);
return r?.Rate ?? throw new InvalidOperationException($"No rate returned for {from}/{to}.");
}
}
public interface ICurrencyConverter
{
ValueTask<decimal> ConvertAsync(decimal amount, string from, string to, CancellationToken ct);
}
public sealed class CurrencyConverter(
IRateProvider provider,
HybridCache cache,
IRateAuditWriter audit,
ILogger<CurrencyConverter> logger) : ICurrencyConverter
{
private static readonly HybridCacheEntryOptions RateTtl = new() { Expiration = TimeSpan.FromMinutes(15) };
public async ValueTask<decimal> ConvertAsync(decimal amount, string from, string to, CancellationToken ct)
{
string key = $"fx:{from}:{to}"; // separator avoids ambiguous keys
decimal rate = await cache.GetOrCreateAsync(key, async innerCt =>
{
decimal fresh = await provider.GetRateAsync(from, to, innerCt); // one call per key even under a stampede
await audit.RecordAsync(from, to, fresh, innerCt);
logger.LogInformation("Fetched FX rate {From}/{To} = {Rate}", from, to, fresh);
return fresh;
}, RateTtl, cancellationToken: ct);
return amount * rate;
}
}
public sealed class RateAuditWriter(IDbContextFactory<AppDbContext> contexts, TimeProvider time) : IRateAuditWriter
{
public async Task RecordAsync(string from, string to, decimal rate, CancellationToken ct)
{
await using AppDbContext db = await contexts.CreateDbContextAsync(ct); // short-lived context per write
db.RateAudits.Add(new RateAudit(from, to, rate, time.GetUtcNow()));
await db.SaveChangesAsync(ct);
}
}
public sealed class RateOptions
{
public required string Provider { get; init; } // "xe" | "rba", validated at startup
public required string XeApiKey { get; init; } // from Key Vault, never in code
}
// Program.cs
builder.Services.AddOptions<RateOptions>()
.BindConfiguration("Rates")
.Validate(o => o.Provider is "xe" or "rba", "Rates:Provider must be 'xe' or 'rba'.")
.ValidateOnStart(); // a typo fails deployment, not checkout
builder.Services.AddHttpClient<XeRateProvider>((sp, c) =>
{
c.BaseAddress = new Uri("https://api.example-fx.com");
c.DefaultRequestHeaders.Add("X-Api-Key", sp.GetRequiredService<IOptions<RateOptions>>().Value.XeApiKey);
}).AddStandardResilienceHandler(); // timeouts, retry with jitter, circuit breaker
builder.Services.AddHttpClient<RbaRateProvider>().AddStandardResilienceHandler();
builder.Services.AddTransient<IRateProvider>(sp => // chosen once per resolution from validated options
sp.GetRequiredService<IOptions<RateOptions>>().Value.Provider == "rba"
? sp.GetRequiredService<RbaRateProvider>()
: sp.GetRequiredService<XeRateProvider>());
builder.Services.AddHybridCache();
builder.Services.AddDbContextFactory<AppDbContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Main")));
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<IRateAuditWriter, RateAuditWriter>();
builder.Services.AddScoped<ICurrencyConverter, CurrencyConverter>();
Blocking: .Result, new HttpClient() per call, the singleton DbContext, the unsynchronised Dictionary and the hard-coded key (plus: rotate the key today). Required: expiry on cached rates, fail-fast provider configuration. Suggested: TimeProvider, structured logs and a metric for provider latency.
Guardrails: analysers VSTHRD002/VSTHRD103 (sync waits), CA2016 (forward CancellationToken), CA2000 (dispose objects), and a banned-API rule (Microsoft.CodeAnalysis.BannedApiAnalyzers) for new HttpClient() and DateTime.Now in application code; secret scanning in the pipeline; ValidateOnBuild in tests; and a review checklist entry: "no static Instance, no new of infrastructure types in services."
A rates service with exactly these problems took checkout down at month-end in one retailer: a memory dump showed about 200 threads blocked in .Result and two threads spinning in Dictionary.FindValue. After the rewrite, p99 for conversion dropped to about 40 ms with a 98% cache hit rate, and provider calls fell from roughly 2,000 a minute to 30.
Checks whether the candidate can review real code by severity, connect creational anti-patterns to production failures, and rewrite with idiomatic .NET DI.
Green flags
DbContext and the Dictionary race.TIME_WAIT, change tracker, bucket corruption).HybridCache, options validation and a proportionate design.Red flags
.Result with GetAwaiter().GetResult().HttpClient static forever, or adds layers of patterns to the rewrite.| # | Problem | Failure in production | How you'd detect it | Fix |
|---|---|---|---|---|
| 1 | Racy static Instance |
Two instances, two contexts; hidden dependencies | Code review; constructor counter | DI registration |
| 2 | Dictionary concurrent writes |
100% CPU, infinite loops, lost entries | dotnet-dump stacks in FindValue/TryInsert |
HybridCache/ConcurrentDictionary |
| 3 | Singleton-owned DbContext |
Concurrency exceptions, memory growth | EF exceptions, dumpheap -stat |
IDbContextFactory, scoped context |
| 4 | .Result |
Thread-pool starvation, timeouts | dotnet-counters thread-pool queue length rising |
async/await end to end |
| 5 | No expiry, no stampede control | Stale rates; provider overload on cold cache | Business reports; provider 429s | TTL + HybridCache single-flight |
| 6 | HttpClient per call |
Socket exhaustion | netstat showing thousands of TIME_WAIT |
Typed client via IHttpClientFactory |
| 7 | switch with default |
Wrong provider silently | Cost anomaly, rate differences | Validated options, fail fast |
| 8 | Hard-coded secret | Credential exposure | Secret scanning | Key Vault configuration, rotation |
| 9 | DateTime.Now, no logs |
Ambiguous audits, invisible failures | Support tickets | TimeProvider, structured logging |
new HttpClient() exhausts socketsHttpClient is a thin wrapper over an HttpMessageHandler (SocketsHttpHandler) that owns a connection pool. A new client means a new pool and a new TCP (and TLS) connection, costing a handshake each time. Disposing closes the connection; the side that closes first keeps the socket in TIME_WAIT (up to 4 minutes on Windows, 60 seconds by default on Linux). At a few hundred calls per second you run out of ephemeral ports. The opposite mistake, one static client forever, ignores DNS changes. IHttpClientFactory rotates handlers (default HandlerLifetime of 2 minutes), and a single client with SocketsHttpHandler.PooledConnectionLifetime achieves the same.
Dictionary spinsEntries are chained through an int[] buckets array and an Entry[] array with next indexes. Two threads inserting during a resize can create a cycle in a chain. A later lookup walks the chain forever. .NET added a concurrent-operation check that throws InvalidOperationException for some cases, but not all races are detected, so the safe rule is: never write to a Dictionary from multiple threads without synchronisation.
HybridCache (.NET 9+)HybridCache (Microsoft.Extensions.Caching.Hybrid) combines an in-process L1 cache with an optional distributed L2 (Redis, SQL Server) and adds stampede protection: concurrent GetOrCreateAsync calls for the same key share a single factory call. Registered with AddHybridCache(). It replaces the hand-written "check dictionary, fetch, store" pattern and its race conditions.
| Option | Pros | Cons |
|---|---|---|
| Factory delegate from validated options (shown) | Simple, fails at startup on bad config | Change needs restart (fine for this) |
| Keyed services + resolver | Supports run-time choice per request | More moving parts |
| Feature flag (Azure App Configuration) | Switch provider without deploy | Needs flag infrastructure and tests for both paths |
.Result, .Wait(), GetAwaiter().GetResult()?dotnet-counters (threadpool-queue-length, threadpool-thread-count).TIME_WAIT sockets with netstat -an | grep TIME_WAIT | wc -l (Linux) during the test.ConvertAsync calls for the same pair and assert the fake provider is called once (HybridCache stampede protection).Microsoft.CodeAnalysis.BannedApiAnalyzers with new HttpClient() banned and check the build fails on the original.The core of the rewrite, with a test that proves stampede protection and expiry:
namespace Currency;
using Microsoft.Extensions.Caching.Hybrid;
public sealed class CurrencyConverter(IRateProvider provider, HybridCache cache) : ICurrencyConverter
{
private static readonly HybridCacheEntryOptions Ttl = new() { Expiration = TimeSpan.FromMinutes(15) };
public async ValueTask<decimal> ConvertAsync(decimal amount, string from, string to, CancellationToken ct)
{
decimal rate = await cache.GetOrCreateAsync(
$"fx:{from}:{to}",
async innerCt => await provider.GetRateAsync(from, to, innerCt), // single flight per key
Ttl,
cancellationToken: ct);
return amount * rate;
}
}
namespace Currency.Tests;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.DependencyInjection;
public sealed class CountingProvider : IRateProvider
{
private int _calls;
public int Calls => _calls;
public async Task<decimal> GetRateAsync(string from, string to, CancellationToken ct)
{
Interlocked.Increment(ref _calls);
await Task.Delay(50, ct); // slow provider makes the stampede visible
return 0.65m;
}
}
public class CurrencyConverterTests
{
[Fact]
public async Task Concurrent_misses_call_the_provider_once()
{
var services = new ServiceCollection();
services.AddHybridCache();
HybridCache cache = services.BuildServiceProvider().GetRequiredService<HybridCache>();
var provider = new CountingProvider();
var sut = new CurrencyConverter(provider, cache);
await Parallel.ForAsync(0, 500, async (_, ct) => await sut.ConvertAsync(100m, "AUD", "USD", ct));
Assert.Equal(1, provider.Calls);
}
}
HttpClient by making it static forever. Why it is wrong: It avoids socket exhaustion but never picks up DNS changes. Instead: Typed clients via IHttpClientFactory, or PooledConnectionLifetime on a single SocketsHttpHandler.Dictionary writes in lock and keeping the design. Why it is wrong: It fixes corruption but not expiry, stampedes or testability. Instead: HybridCache with a TTL.DbContext field [ThreadStatic] or locking around it. Why it is wrong: Still a long-lived context with a growing change tracker; thread-static breaks with async. Instead: IDbContextFactory<T> per operation, or a scoped consumer..Result with GetAwaiter().GetResult(). Why it is wrong: It blocks exactly the same way; only the exception wrapping changes. Instead: Make Convert async and propagate to callers.appsettings.json in the repo. Why it is wrong: It's still a committed secret. Instead: Key Vault-backed configuration (managed identity), user secrets locally, and rotate the exposed key.switch default branch "for safety". Why it is wrong: It turns a configuration error into silently wrong rates and costs. Instead: Validate options at startup and fail fast.This code is a catalogue of creational mistakes: every object that should be owned by the container (singleton, client, context, provider) is created by hand. The senior move is to see that one root cause, explain the production impact of each symptom in order, and fix it with the framework's mechanisms rather than with more patterns.
| Finding | Framework mechanism | Why not hand-roll |
|---|---|---|
| Static singleton | AddScoped/AddSingleton |
Lifetimes, disposal, testability |
new HttpClient() |
AddHttpClient<T>() + AddStandardResilienceHandler() |
Handler pooling, rotation, resilience |
new DbContext() |
AddDbContext/AddDbContextFactory |
Correct per-operation lifetime |
Dictionary cache |
HybridCache |
Expiry, stampede protection, optional L2 |
switch factory |
Options + ValidateOnStart, keyed services |
Fail-fast configuration, Open/Closed |
| Hard-coded key | Key Vault configuration provider | Rotation, audit, no secrets in Git |
I'd also keep the rewrite proportionate. Two providers chosen by configuration don't need a plugin framework. To show the fix worked, I'd compare before and after on thread-pool queue length, TIME_WAIT socket count, cache hit rate and p99 latency under the same load test.
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.
A captive dependency is a service held by a consumer that lives longer than it should. Most often a scoped service (such as DbContext or a current-user service) is injected into a singleton, so it is created once and shared by every request. That leads to cross-user data leaks, "A second operation was started on this context instance", stale tracked entities and ObjectDisposedException.
ValidateScopes throws when a scoped service is resolved from the root or from a singleton. ValidateOnBuild checks every registration when the provider is built. Both are on only in Development by default, so turn them on in tests too.
The fix is either to make the consumer scoped, or to inject IServiceScopeFactory and create a scope per unit of work. A transient captured by a singleton is also captive, and validation won't catch it.
This is a Strategy (IPaymentGateway) chosen by a factory. There are three DI-friendly ways to do it:
AddKeyedScoped<IPaymentGateway, StripeGateway>("stripe"), then inject with [FromKeyedServices("stripe")]. This only works when the key is known at compile time.IEnumerable<IPaymentGateway> resolver: each gateway exposes a Provider key, and a resolver builds a FrozenDictionary from them. There's no container access, but every gateway is constructed.IPaymentGatewayResolver.Resolve(provider) calls GetRequiredKeyedService inside the composition root. It builds only the gateway you need.To avoid a service locator, business code depends on a narrow typed resolver, never on IServiceProvider. Map unknown keys to a domain error, and validate the configured keys at startup.
How to tell it (STAR)
**S:** At [company] our checkout timed out at [month-end] peak, and two instances sat at 100% CPU. **T:** As [the senior on call], I had to restore checkout and fix the root cause in the shared currency service. **A:** A memory dump showed [~200] threads blocked on `.Result` and two threads spinning in a corrupted `Dictionary`, and `netstat` showed [~14,000] sockets in `TIME_WAIT` from `new HttpClient()` per call. We restarted and scaled out, hot-fixed the cache and client, and then I led a rewrite onto DI with typed clients, a resilience handler, `HybridCache` and short-lived `DbContext`s, plus rotating the hard-coded key. **R:** p99 for conversion dropped to [~40 ms] with a [98%] cache hit rate, provider calls fell from [~2,000] to [~30] a minute, and the analysers have blocked [several] similar changes since.
Last updated 18 Nov 2026.