5.5 — Conventional Middleware Classes¶
← Roadmap · Section: 5. Middleware and the Request Pipeline Prev: 5.4 Inline middleware · Next: 5.6 IMiddleware factory
Markers: 🔥 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
Conventional middleware is middleware written as a class with a constructor taking
RequestDelegate next, and a method called InvokeAsync.
- It implements no interface. The framework finds
InvokeAsyncby name, using reflection. - The class is created once, at startup — it is effectively a singleton.
- Scoped services go in the
InvokeAsyncparameters, not the constructor. That is the one rule that matters.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Conventional middleware | a class shape | A class with a RequestDelegate constructor parameter and an InvokeAsync method. |
InvokeAsync |
a method, found by name | Where the work happens. Must return Task and take HttpContext first. |
Invoke |
the older name | Also accepted. InvokeAsync is preferred; defining both throws. |
RequestDelegate next |
a constructor parameter | The rest of the pipeline, captured once at startup. |
UseMiddleware<T>() |
an extension method | Registers the class into the pipeline. |
| Convention-based | a discovery style | Found by name, not by an interface. Misspelling compiles and silently fails. |
| Singleton lifetime | what middleware gets | One instance for the whole application, shared by every concurrent request. |
| Method injection | the fix for scoped services | Extra InvokeAsync parameters are resolved per request from the request scope. |
| Registration extension | a static method | UseSomething(this IApplicationBuilder). Makes your middleware read like the built-in ones. |
The concept¶
The shape¶
public class RequestTimingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestTimingMiddleware> _logger;
// Constructor — runs ONCE, at startup
public RequestTimingMiddleware(
RequestDelegate next,
ILogger<RequestTimingMiddleware> logger)
{
_next = next;
_logger = logger;
}
// InvokeAsync — runs on EVERY request
public async Task InvokeAsync(HttpContext context)
{
var start = Stopwatch.GetTimestamp();
await _next(context);
var ms = Stopwatch.GetElapsedTime(start).TotalMilliseconds;
_logger.LogInformation("{Path} → {Status} in {Ms:F0}ms",
context.Request.Path, context.Response.StatusCode, ms);
}
}
Registered with:
With C# 12 primary constructors it is shorter:
public class RequestTimingMiddleware(
RequestDelegate next,
ILogger<RequestTimingMiddleware> logger)
{
public async Task InvokeAsync(HttpContext context)
{
var start = Stopwatch.GetTimestamp();
await next(context);
logger.LogInformation("{Path} took {Ms:F0}ms",
context.Request.Path, Stopwatch.GetElapsedTime(start).TotalMilliseconds);
}
}
⚠️ It implements no interface¶
This is the first thing to know, and it mirrors the Startup.cs convention
(4.4).
There is no IMiddleware to implement here. The framework looks for a method named
InvokeAsync (or Invoke) using reflection.
public class MyMiddleware(RequestDelegate next)
{
// Typo — compiles fine, never runs
public async Task InvokAsync(HttpContext context) // missing 'e'
{
await next(context);
}
}
app.UseMiddleware<MyMiddleware>() throws at startup with
"No public 'InvokeAsync' or 'Invoke' method found" — which is at least loud, unlike the
Startup.cs equivalent that fails silently.
Rules for the method:
- Named
InvokeAsyncorInvoke— not both, or it throws - Returns
Task - First parameter must be
HttpContext - Further parameters are resolved from DI per request
How it works¶
The simple version — created once¶
The class is instantiated a single time, when the pipeline is built. Not per request.
That means:
- The constructor runs once, at startup
- The instance is shared by every concurrent request
- Any field you set is shared across all of them
public class CountingMiddleware(RequestDelegate next)
{
private int _count; // ⚠️ shared by ALL requests
public async Task InvokeAsync(HttpContext context)
{
_count++; // ⚠️ RACE CONDITION
await next(context);
}
}
That _count++ is three operations and two threads can interleave
(2.18). Use Interlocked.Increment, or
better, do not keep mutable state in middleware at all.
How it actually works — the scoped service problem ⚠️¶
This is the most important thing in the note.
Because the class is a singleton, injecting a scoped service into the constructor captures it forever:
// ✗ BROKEN
public class AuditMiddleware(RequestDelegate next, AppDbContext db)
{
public async Task InvokeAsync(HttpContext context)
{
db.AuditLog.Add(new AuditEntry(context.Request.Path));
await db.SaveChangesAsync();
await next(context);
}
}
The middleware is built once, so db is resolved once and held for the application's lifetime.
That DbContext is now shared by every concurrent request — it is not thread-safe, and its
change tracker grows without limit. This is the captive dependency problem
(6.4).
In Development you usually get a startup exception, because scope validation is on. In production it is off by default, so the app starts and misbehaves under load — which is exactly why this bug reaches production.
The fix: put scoped services in the InvokeAsync signature.
// ✓ CORRECT
public class AuditMiddleware(RequestDelegate next)
{
public async Task InvokeAsync(HttpContext context, AppDbContext db)
{
// ^^^^^^^^^^^^^^^
// Resolved fresh from THIS REQUEST's scope, every time
db.AuditLog.Add(new AuditEntry(context.Request.Path));
await db.SaveChangesAsync();
await next(context);
}
}
Extra parameters on InvokeAsync are resolved per request from context.RequestServices, so
each request gets its own instance.
The rule to remember: singletons in the constructor, scoped in InvokeAsync.
Loggers, IOptions<T>, IHttpClientFactory and configuration are all singletons — constructor
is correct for those.
The deeper detail — the extension method¶
Every built-in middleware is exposed through an extension method, and yours should be too:
public static class RequestTimingMiddlewareExtensions
{
public static IApplicationBuilder UseRequestTiming(this IApplicationBuilder app)
=> app.UseMiddleware<RequestTimingMiddleware>();
}
// Program.cs now reads consistently
app.UseExceptionHandler();
app.UseRequestTiming(); // ← indistinguishable from built-in
app.UseAuthentication();
Two benefits beyond style: the middleware class can be internal, keeping it out of your public
API surface, and you can validate configuration or add related services inside the extension
method.
Passing options¶
UseMiddleware<T> forwards extra arguments to the constructor:
public class RateLimitMiddleware(RequestDelegate next, int maxPerMinute)
{
public async Task InvokeAsync(HttpContext context) { /* ... */ }
}
app.UseMiddleware<RateLimitMiddleware>(100);
But prefer IOptions<T> for anything non-trivial, because it participates in configuration
binding and validation (7.6):
public class RateLimitMiddleware(
RequestDelegate next,
IOptions<RateLimitOptions> options)
{
private readonly RateLimitOptions _options = options.Value;
}
⚠️ Note IOptions<T> is a singleton and safe in the constructor. IOptionsSnapshot<T> is
scoped and must go in InvokeAsync instead — a subtle version of the same trap.
Code¶
A complete, realistic middleware with its extension method:
internal class CorrelationIdMiddleware(
RequestDelegate next,
ILogger<CorrelationIdMiddleware> logger) // singleton — constructor is fine
{
private const string HeaderName = "X-Correlation-Id";
public async Task InvokeAsync(HttpContext context)
{
var correlationId = context.Request.Headers[HeaderName].FirstOrDefault()
?? Guid.NewGuid().ToString("N");
context.Items[HeaderName] = correlationId;
// Set the header before anything downstream writes the response
context.Response.OnStarting(() =>
{
context.Response.Headers[HeaderName] = correlationId;
return Task.CompletedTask;
});
// Put it in the log scope so EVERY log line for this request carries it
using (logger.BeginScope(new Dictionary<string, object>
{
["CorrelationId"] = correlationId
}))
{
await next(context);
}
}
}
public static class CorrelationIdMiddlewareExtensions
{
public static IApplicationBuilder UseCorrelationId(this IApplicationBuilder app)
=> app.UseMiddleware<CorrelationIdMiddleware>();
}
Three deliberate choices worth explaining:
OnStartingrather than setting the header afternext, because by then the response has started and headers are read-only (5.8).BeginScopewrappingnext, so every log entry produced anywhere downstream carries the correlation ID automatically (18.4).internal, because the extension method is the public surface.
Testing it¶
Unlike inline middleware, this is straightforwardly unit testable:
[Fact]
public async Task Adds_correlation_id_when_none_supplied()
{
var context = new DefaultHttpContext();
var nextCalled = false;
var middleware = new CorrelationIdMiddleware(
next: _ => { nextCalled = true; return Task.CompletedTask; },
logger: NullLogger<CorrelationIdMiddleware>.Instance);
await middleware.InvokeAsync(context);
Assert.True(nextCalled);
Assert.True(context.Items.ContainsKey("X-Correlation-Id"));
}
DefaultHttpContext is a real, usable HttpContext for tests, and next is just a delegate
you supply — so there is no framework to stand up. That testability is the main reason to
prefer a class over inline.
Interview questions¶
Q: How do you write custom middleware as a class?
You write a plain class with a constructor taking a RequestDelegate — the rest of the pipeline
— and a method named InvokeAsync that takes HttpContext and returns Task. Inside it you do
your work, call the delegate to continue down the pipeline, and optionally do more work after it
returns. You register it with app.UseMiddleware<T>(), usually wrapped in an extension method
so it reads like the built-in ones. Notably the class implements no interface — the framework
locates InvokeAsync by name using reflection.
Q: What lifetime does conventional middleware have?
Singleton. The class is instantiated once when the pipeline is built, not per request, so a
single instance is shared across every concurrent request. That has two consequences: any
mutable field is shared state needing thread safety, and injecting a scoped service into the
constructor captures one instance for the life of the application. For a DbContext that is
both a thread-safety bug and a memory leak, because its change tracker never resets.
Q: How do you use a scoped service like DbContext in middleware?
Put it in the InvokeAsync signature rather than the constructor. Extra parameters on that
method are resolved per request from the request's own DI scope, so each request gets its own
instance. The rule I remember is singletons in the constructor, scoped services in
InvokeAsync. A subtlety worth knowing is that IOptions<T> is a singleton and safe in the
constructor, but IOptionsSnapshot<T> is scoped and has to go in the method.
Q: What happens if you misspell InvokeAsync?
You get an exception at startup saying no public InvokeAsync or Invoke method was found, so
the failure is loud and immediate. That is better than the equivalent mistake in the old
Startup.cs convention, where a misspelled ConfigureServices compiled and simply never ran.
Worth also knowing that defining both Invoke and InvokeAsync on the same class throws,
because the framework cannot decide which one you meant.
Traps ⚠️¶
- Injecting a scoped service into the constructor is a captive dependency. Development catches it; production does not, by default.
- The class is a singleton, so mutable fields are shared across concurrent requests.
IOptionsSnapshot<T>is scoped and cannot go in the constructor, unlikeIOptions<T>.- Defining both
InvokeandInvokeAsyncthrows at startup. - The first
InvokeAsyncparameter must beHttpContext. Other orders fail. InvokeAsyncmust returnTask, notvoidorValueTask.- Forgetting to call
nextends the pipeline silently. - Setting headers after
await nextthrows — useOnStarting.
Related¶
- 5.4 Inline middleware — the simpler alternative
- 5.6 IMiddleware factory — the per-request alternative
- 5.8 HttpContext —
ItemsandOnStarting - 6.4 Captive dependencies — the trap in detail
- 7.6 Options pattern —
IOptionsvsIOptionsSnapshot - 18.4 Log scopes —
BeginScope - 2.18 Thread safety — shared mutable fields