anantbhandarkar/make-it-right/mir-backend-dotnet

Claude Code and agent skill by anantbhandarkar/make-it-right

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Make It Right (.NET runtime tier). CLR/CoreCLR reliability footguns shared across every .NET backend framework. Covers: runtime version currency (.NET 10 is the current LTS; 8 and 9 leave support 10 Nov 2026), sync-over-async deadlock and thread-pool starvation (.Result/.Wait()/.GetAwaiter().GetResult()), ConfigureAwait(false) in library code, ValueTask misuse, IDisposable/IAsyncDisposable discipline and HttpClient socket/DNS exhaustion, DbContext thread-safety and lifetime, DI captive dependency (Scoped or Transient injected into Singleton) with ValidateScopes only running in Development, CancellationToken propagation, BackgroundService host-kill semantics, the DATAS server-GC default, trimming/Native AOT reflection breakage, and CLR-level security (BinaryFormatter removal, ProcessStartInfo.ArgumentList, Path.Combine traversal, SSRF via HttpClient redirects, NuGet lockfile and package source mapping). Chains: mir-backend -> this -> framework module. TRIGGER when the backend runtime is .NET / CLR — any C# or F# service. SKIP for Node, JVM, Go, Rust, Python, Ruby, PHP, and BEAM runtimes (each has its own mir-backend-<runtime> tier), and SKIP for ASP.NET Core and EF Core mechanics — middleware order, model binding, antiforgery, EF Core queries, and migrations live in mir-backend-dotnet-aspnetcore.

Install

npx vskill@latest install anantbhandarkar/make-it-right/mir-backend-dotnet

SKILL.md

The same SKILL.md was published earlier as anantbhandarkar/make-it-right/mir-backend-dotnet.

/mir-backend-dotnet · Make It Right (.NET runtime)

The middle tier. mir-backend decides what is correct (any language). The framework module (e.g. mir-backend-dotnet-aspnetcore) knows the library's mechanics. This tier owns what's true for all .NET backends because they run on the CLR — the async model, thread pool, DI container, and object lifetime rules that ASP.NET Core, gRPC services, background workers, and SignalR hubs all inherit.

Runtime assumed (verified 13 Aug 2026): .NET 10 — the current LTS, shipped Nov 2025, supported to Nov 2028. Latest patch is 10.0.11 (11 Aug 2026); the corresponding .NET 9 / .NET 8 patches are 9.0.19 and 8.0.30.

.NET 8 (LTS) and .NET 9 (STS) both reach end of support on 10 Nov 2026 — the same day, because STS moved to a 24-month window. After that date neither gets security fixes. A new service targeting net8.0 or net9.0 today is a migration item with under three months of runway, not a default; say so at Gate 0 rather than accepting the TFM silently. .NET 11 is the next STS (expected Nov 2026) and is in preview as of this writing — do not target it in production.

Load order: mir-backend → mir-backend-dotnet → <framework module>.

The CLR footguns AI walks into (framework-agnostic)

1. Sync-over-async — the classic deadlock and thread-pool starvation trap

Calling .Result, .Wait(), or .GetAwaiter().GetResult() on a Task or ValueTask from synchronous code is the #1 async bug on .NET. In runtimes that have a SynchronizationContext (old ASP.NET, WinForms, WPF, Blazor Server), the awaited continuation is posted back to the same context — but the calling thread is blocking that context, so you deadlock. In ASP.NET Core (no sync context) you dodge the deadlock but still consume a thread-pool thread for the full duration of the I/O wait, which starves the pool under concurrent load and produces the latency cliff that looks identical to "the server slows down after 30 concurrent users."

csharp
// WRONG — blocks a thread-pool thread; deadlocks in sync-context runtimes
var result = GetDataAsync().Result;
var result = GetDataAsync().GetAwaiter().GetResult();
// RIGHT — async all the way
var result = await GetDataAsync();

Fix: async all the way from the top. Every caller must be async; there is no safe place to block. If you genuinely need a blocking entry point (console bootstrap, legacy sync API), use Task.Run(() => AsyncWork()).GetAwaiter().GetResult() only at the outermost boundary — never inside a library or middleware.

2. ConfigureAwait(false) in library code

In apps with a SynchronizationContext the continuation after await captures the current context and marshals back to it — necessary for UI/Blazor but adds overhead and causes deadlock risk when called by sync-over-async callers. Library code must `ConfigureAwait(false)` on every `await` to avoid capturing the caller's context:

csharp
// Library method — WRONG (may deadlock callers with sync context)
public async Task<T> ReadAsync() {
var data = await _store.GetAsync(); // captures context
return Transform(data);
}
// RIGHT
public async Task<T> ReadAsync() {
var data = await _store.GetAsync().ConfigureAwait(false);
return Transform(data);
}

ASP.NET Core itself has no SynchronizationContext, so omitting ConfigureAwait(false) in an ASP.NET Core-only project is usually safe — but a library you ship may be consumed by Blazor Server or WPF; always add it in library/NuGet code. AI routinely omits it everywhere or adds it nowhere.

ConfigureAwait(false) is the same as ConfigureAwait(ConfigureAwaitOptions.None). The enum overload adds two flags worth knowing:

OptionUse it for
ConfigureAwaitOptions.Noneidentical to ConfigureAwait(false) — library default
ConfigureAwaitOptions.ContinueOnCapturedContextidentical to ConfigureAwait(true)
ConfigureAwaitOptions.SuppressThrowingawait a task for completion but do not rethrow its exception — replaces try { await t; } catch { }, which also swallows cancellation
ConfigureAwaitOptions.ForceYieldingforce an async continuation even when the task already completed

SuppressThrowing on a Task<T> throws ArgumentOutOfRangeException — it is only valid on non-generic Task, because there is no result to hand back.

3. ValueTask — await at most once, never cache or await twice

ValueTask / ValueTask<T> exists for hot-path allocation savings on synchronous-fast paths. Its constraints depend on the backing representation, which the caller usually cannot see, and the compiler enforces none of them:

  • Await it at most once. A ValueTask wrapping a result or a Task tolerates repeated awaits, but an IValueTaskSource-backed one generally supports a single consumption — awaiting twice (or .Result after an await) then reads a recycled object. Since you cannot tell which you got, treat one await as the rule.
  • Don't store it and await later. The source may have been recycled by the time you come back.
  • Convert to `Task` before sharing: call AsTask() once and share the resulting Task.
csharp
// WRONG — awaited twice
var vt = GetValueAsync();
var a = await vt;
var b = await vt; // undefined behavior
// WRONG — cached, then awaited later
_cachedVt = GetValueAsync();
// ... later ...
var result = await _cachedVt; // may be recycled
// RIGHT — await immediately, convert if you need to share
var result = await GetValueAsync();
// or
var task = GetValueAsync().AsTask();

Use ValueTask only when profiling proves the allocation matters (hot-loop network reads, high-frequency polling). Default to Task.

4. Thread-pool starvation — blocking calls under load

The CLR thread pool grows using hill-climbing plus starvation detection, not a fixed injection interval — the old "one thread per 500 ms" figure is obsolete, but the shape of the failure is unchanged: blocking calls (sync I/O, Thread.Sleep, heavy CPU on pool threads, lock contention) consume workers faster than the pool reacts. Symptoms: all endpoints slow simultaneously, ThreadPool.GetAvailableThreads drops to near zero, and the queue climbs while CPU sits idle.

  • Keep every I/O call async so threads return to the pool during the wait.
  • CPU-bound work: Task.Run(...) to explicitly schedule on a pool thread and await it, or use a dedicated BackgroundService with bounded parallelism.
  • Never call Thread.Sleep on a pool thread — await Task.Delay(...) instead.
  • SemaphoreSlim.Wait() blocks; await SemaphoreSlim.WaitAsync(ct) does not. Same for lock around an await — you cannot await inside lock, and AI works around it with .Result. Use SemaphoreSlim(1,1) instead.
  • Monitor with dotnet-counters monitor --counters System.Runtime and watch ThreadPool Queue Length and ThreadPool Thread Count. A queue length that climbs while CPU is idle means blocked threads, not slow code.
  • ThreadPool.SetMinThreads(n, n) buys time by pre-growing the pool. It is a mitigation for a blocking call you have not removed yet, not a fix.
5. IDisposable / using scopes — not optional

Every IDisposable (streams, HttpClient (if raw), SqlConnection, DbContext, SemaphoreSlim, CancellationTokenSource) must be disposed. Failure patterns:

  • Forgetting using on a DbContext created manually → connection leak.
  • Creating HttpClient instances per-request (common AI pattern) → socket exhaustion (TIME_WAIT). Use IHttpClientFactory or a long-lived shared client; never new HttpClient() per request.
  • CancellationTokenSource not disposed → timer leak if a delay was scheduled.
  • Using using on a type that implements IAsyncDisposable (DbContext, SqlConnection, FileStream opened async, ServiceProvider) runs the synchronous disposal path or none at all. Write await using.
csharp
// WRONG — new HttpClient per request → socket exhaustion
async Task<string> CallApi() {
using var client = new HttpClient(); // still wrong — see below
return await client.GetStringAsync(url);
}
// RIGHT — factory or singleton
public class MyService(IHttpClientFactory factory) {
async Task<string> CallApi() {
using var client = factory.CreateClient("myApi");
return await client.GetStringAsync(url);
}
}

The opposite failure — one static `HttpClient` forever: DNS is resolved when a new connection is opened, so a client that keeps reusing a pooled connection indefinitely never re-resolves and keeps talking to a decommissioned IP after a failover or blue/green cutover. IHttpClientFactory rotates handlers (default handler lifetime 2 minutes) and avoids this. If you must hold your own client, bound the connection lifetime explicitly:

csharp
var handler = new SocketsHttpHandler {
PooledConnectionLifetime = TimeSpan.FromMinutes(2) // forces periodic DNS re-resolution
};
var client = new HttpClient(handler); // safe to keep for the process lifetime
6. DbContext is NOT thread-safe — never share across threads or store in a singleton

DbContext (EF Core) tracks entity state in a non-thread-safe identity map. AI commonly produces two bugs:

Bug A — singleton or static DbContext: the context lives for the app lifetime, its change tracker grows unboundedly, and concurrent requests corrupt each other's entity state.

Bug B — sharing across `Task.WhenAll` / `Parallel.ForEach`: concurrent operations on one context produce non-deterministic exceptions (InvalidOperationException: A second operation was started on this context).

csharp
// WRONG — DbContext injected into a singleton service
public class MySingletonService {
private readonly AppDbContext _db; // Scoped captured in Singleton = captive dependency
public MySingletonService(AppDbContext db) => _db = db;
}
// RIGHT — use IDbContextFactory<T> in long-lived services
public class MySingletonService(IDbContextFactory<AppDbContext> factory) {
public async Task DoWork() {
await using var db = await factory.CreateDbContextAsync();
// short-lived context, disposed after the unit of work
}
}
7. DI lifetime — the captive dependency bug

The .NET DI container does not stop a Singleton from capturing a Scoped service. The Singleton is created once and holds that dependency for the whole app lifetime. For DbContext that means one shared context across all requests: cross-request data bleed and threading corruption. Capturing a Transient is legal, but the instance then lives as long as the Singleton — a problem when it holds request state or owns something disposable.

csharp
// WRONG
services.AddSingleton<MyService>(); // captures Scoped DbContext in ctor
services.AddDbContext<AppDbContext>(); // Scoped by default
// RIGHT — validate at build time, in EVERY environment
builder.Host.UseDefaultServiceProvider((_, o) => {
o.ValidateScopes = true; // Scoped resolved from root/Singleton throws — this is the captive-dep check
o.ValidateOnBuild = true; // walks registrations at Build() and throws if one cannot be constructed
});

The trap that makes this bite in production specifically: the default host turns ValidateScopes and ValidateOnBuild on only when the environment is Development. In Staging or Production they are off. So the captive dependency does not throw — it constructs, and one DbContext quietly serves every request. Pass the options unconditionally as above (the two-argument overload gives you the HostBuilderContext if you need to branch, but do not branch on environment here). ValidateOnBuild costs a few milliseconds at boot; it is not a perf trade worth making.

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
15
7-day trend score
14

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/anantbhandarkar/make-it-right/mir-backend-dotnet/badge)](https://verified-skill.com/skills/anantbhandarkar/make-it-right/mir-backend-dotnet)

Something wrong with this skill or its page? Tell us.