Library

Volume 3 · .NET & C# Deep Dive

Notebook
Sign in

Section 1

.NET Core Architecture (middleware pipeline, DI lifetimes: Singleton/Scoped/Transient with pitfalls)

930 words · about 4 min

1.1 CLR Architecture

┌─────────────────────────────────────────────────────┐
│                   .NET Application                    │
├─────────────────────────────────────────────────────┤
│  BCL (Base Class Library) — System.*, Collections    │
├─────────────────────────────────────────────────────┤
│  CLR (Common Language Runtime)                        │
│  ┌──────────┐ ┌──────────┐ ┌──────────────────────┐│
│  │   JIT    │ │   GC     │ │   Type System        ││
│  │ Compiler │ │(Garbage  │ │  (Metadata, Reflect) ││
│  │          │ │Collector)│ │                       ││
│  └──────────┘ └──────────┘ └──────────────────────┘│
│  ┌──────────┐ ┌──────────┐ ┌──────────────────────┐│
│  │ Thread   │ │Exception │ │   Security /         ││
│  │ Pool     │ │ Handling │ │   Code Access        ││
│  └──────────┘ └──────────┘ └──────────────────────┘│
├─────────────────────────────────────────────────────┤
│                Operating System                       │
└─────────────────────────────────────────────────────┘

C# source is compiled by Roslyn into IL (Intermediate Language), which is JIT-compiled to native code method-by-method on first call. .NET 8+ tiers this: Tier 0 (Quick JIT, fast/unoptimized) → Tier 1 (fully optimized, after ~30 calls) → OSR (on-stack replacement, optimizes long-running loops mid-execution) → Native AOT (compile-to-native at build time, eliminating JIT startup cost entirely, at the expense of limited runtime reflection).

1.2 Middleware Pipeline

Request → [Exception Handler] → [HTTPS Redirect] → [Static Files] → [Routing]
    → [CORS] → [Authentication] → [Authorization] → [Endpoint/Controller]
    → Response flows back through the same pipeline in reverse
public class RequestTimingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;

    public RequestTimingMiddleware(RequestDelegate next, ILogger<RequestTimingMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var sw = Stopwatch.StartNew();
        context.Response.OnStarting(() =>
        {
            context.Response.Headers["X-Response-Time"] = $"{sw.ElapsedMilliseconds}ms";
            return Task.CompletedTask;
        });

        await _next(context); // Call next middleware

        _logger.LogInformation(
            "{Method} {Path} responded {StatusCode} in {ElapsedMs}ms",
            context.Request.Method, context.Request.Path,
            context.Response.StatusCode, sw.ElapsedMilliseconds);
    }
}

// Registration (ORDER MATTERS!)
app.UseExceptionHandler("/error");
app.UseHttpsRedirection();
app.UseRouting();
app.UseMiddleware<RequestTimingMiddleware>();
app.UseCors("AllowFrontend");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

Middleware order is not cosmetic — authentication must run before authorization, exception handling must wrap everything, and routing must occur before endpoint-specific middleware can inspect the matched endpoint.

1.3 Dependency Injection Lifetimes

Lifetime Behavior Use For
Transient New instance every time requested Lightweight, stateless services
Scoped One instance per HTTP request / scope DbContext, Unit of Work, API clients tied to a request
Singleton One instance for app lifetime Configuration, caching, connection pools, HttpClient
builder.Services.AddTransient<IEmailService, SmtpEmailService>();
builder.Services.AddScoped<IOrderRepository, EfOrderRepository>();
builder.Services.AddSingleton<ICacheService, RedisCacheService>();

// CAPTIVE DEPENDENCY ANTI-PATTERN:
// Singleton service depends on Scoped service → Scoped lives forever!

// WRONG:
public class SingletonService  // Registered as Singleton
{
    private readonly IScopedService _scoped; // Lives forever now — captured at first resolution!
}

// FIX: Inject IServiceScopeFactory and resolve per-use
public class SingletonService
{
    private readonly IServiceScopeFactory _scopeFactory;

    public async Task DoWork()
    {
        using var scope = _scopeFactory.CreateScope();
        var scoped = scope.ServiceProvider.GetRequiredService<IScopedService>();
    }
}

// Keyed Services (.NET 8+)
builder.Services.AddKeyedScoped<INotificationService, EmailService>("email");
builder.Services.AddKeyedScoped<INotificationService, SmsService>("sms");

public class OrderController(
    [FromKeyedServices("email")] INotificationService emailService,
    [FromKeyedServices("sms")] INotificationService smsService)
{ }

The captive dependency anti-pattern is one of the most commonly asked DI questions: if a Singleton captures a Scoped instance in its constructor, that Scoped instance is frozen at container build time and reused for the app’s lifetime — silently breaking per-request isolation (e.g., a DbContext shared across all requests, causing thread-safety violations and stale data). ASP.NET Core’s built-in container actually throws at startup with scope validation enabled (ValidateScopes = true, on by default in Development) — but it’s still worth knowing how to explain and avoid it.

Interview Q&A — Section 1

Q1: Explain Scoped, Transient, and Singleton. What’s the captive dependency problem?

A: Transient creates a new instance every time it’s requested — good for cheap, stateless services. Scoped creates one instance per HTTP request (or explicit scope) — the right choice for DbContext and anything that should be consistent within a single request but isolated across requests. Singleton creates one instance for the app’s lifetime — appropriate for shared, thread-safe resources like configuration or a connection pool. The captive dependency problem occurs when a Singleton injects a Scoped service directly: the Scoped instance gets captured at the Singleton’s construction time and lives forever, breaking per-request isolation. The fix is to inject IServiceScopeFactory into the Singleton and create a new scope per unit of work.

Q2: Why does middleware order matter, and what’s a real incident you’d expect from misordering it?

A: Each middleware wraps the next one, so ordering determines both what runs before the request reaches the endpoint and what runs on the way back. If UseAuthorization() is placed before UseAuthentication(), authorization checks run against an unauthenticated HttpContext.User, so every request gets rejected regardless of credentials. Similarly, exception-handling middleware must be first in the pipeline, or exceptions thrown by later middleware (like the authentication handler) escape unhandled.

Q3: What is Native AOT and what tradeoffs does it involve?

A: Native AOT compiles the application straight to native machine code at publish time, eliminating JIT warmup — startup drops to single-digit milliseconds and the deployed footprint shrinks, which is valuable for serverless/Lambda-style cold starts. The tradeoff is that runtime code generation is restricted: full reflection, runtime Assembly.Load, and dynamic proxy-based libraries (some ORMs, some DI conveniences) don’t work without adaptation — you typically need source-generated serializers (System.Text.Json source generators) and AOT-compatible DI registration.