5.6 — Factory-Based Middleware (IMiddleware)¶
← Roadmap · Section: 5. Middleware and the Request Pipeline Prev: 5.5 Conventional middleware · Next: 5.7 Short-circuiting
Markers: ⭐ ⚠️ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
IMiddleware is the interface-based alternative to conventional middleware. Instead of the
framework creating one instance at startup, it asks the DI container for one per request.
- Because it is resolved per request, scoped services work in the constructor — no method injection needed.
- It is strongly typed: implement the interface and the compiler checks you got it right.
- You must register it in DI yourself, and forgetting that is the one gotcha.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
IMiddleware |
an interface in Microsoft.AspNetCore.Http |
Has one method: InvokeAsync(HttpContext, RequestDelegate). |
| Factory-based middleware | a middleware style | The instance is produced by a factory — the DI container — on each request. |
IMiddlewareFactory |
an interface | What creates the instance. The default implementation resolves from DI. |
| Conventional middleware | the other style | A class found by convention, created once. See 5.5. |
| Per-request activation | a lifetime behaviour | A new instance for every request, so constructor injection of scoped services is safe. |
AddScoped<T>() |
a registration method | How you normally register IMiddleware implementations. |
AddTransient<T>() |
a registration method | Also works. Effectively the same here, since one instance is used per request. |
UseMiddleware<T>() |
an extension method | Same call as conventional — the framework detects that T implements IMiddleware. |
The concept¶
The problem it solves¶
Conventional middleware is created once, at startup
(5.5). That makes it effectively a singleton, so you cannot
inject scoped services into its constructor — you have to add them as InvokeAsync parameters
instead.
That works, but it has costs:
- The class's dependencies are split across two places, which reads oddly.
- Method injection is not obvious to someone unfamiliar with the convention.
- Nothing about the class says it is a singleton.
IMiddleware fixes all three by changing when the instance is created. Ask DI for a fresh
instance per request, and constructor injection just works like it does everywhere else in your
application.
A picture: conventional middleware is one permanent employee handling every customer. Factory-based middleware is hiring a temp for each customer — more overhead per customer, but each one can carry that customer's paperwork without any risk of mixing it up.
How it works¶
The simple version — the shape¶
public class AuditMiddleware : IMiddleware
{
private readonly AppDbContext _db; // SCOPED — and that is fine
private readonly ILogger<AuditMiddleware> _logger;
public AuditMiddleware(AppDbContext db, ILogger<AuditMiddleware> logger)
{
_db = db;
_logger = logger;
}
// The interface method. Note 'next' is a PARAMETER, not a constructor argument.
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
_db.AuditLog.Add(new AuditEntry(context.Request.Path, DateTimeOffset.UtcNow));
await _db.SaveChangesAsync();
await next(context);
}
}
Two structural differences from conventional middleware:
- No
RequestDelegatein the constructor. It arrives as a method parameter instead. AppDbContextin the constructor is safe, because a new instance is created per request.
⚠️ Registration — the gotcha¶
Factory-based middleware requires two steps, not one:
// 1. Register it in DI — EASY TO FORGET
builder.Services.AddScoped<AuditMiddleware>();
var app = builder.Build();
// 2. Add it to the pipeline
app.UseMiddleware<AuditMiddleware>();
Miss the first step and you get a runtime exception on the first request:
No service for type 'AuditMiddleware' has been registered.
Conventional middleware needs no registration at all, so people forget. It is a loud failure, at least — but it happens on the first request rather than at startup.
You can validate at startup by enabling
ValidateOnBuild (4.5).
Conventional vs factory-based¶
| Conventional | Factory-based (IMiddleware) |
|
|---|---|---|
| Implements an interface | No — found by name | Yes |
| Instances | One, at startup | One per request |
RequestDelegate |
Constructor parameter | Method parameter |
| Scoped services | InvokeAsync parameters only |
Constructor — normal DI |
| Must register in DI | No | Yes |
| Compile-time checked | No | Yes |
| Allocation per request | None | One instance |
How it actually works — the factory¶
The framework resolves an IMiddlewareFactory and calls it per request:
// Roughly what happens per request
var factory = context.RequestServices.GetRequiredService<IMiddlewareFactory>();
var middleware = factory.Create(typeof(AuditMiddleware)); // resolves from request scope
try
{
await middleware.InvokeAsync(context, next);
}
finally
{
factory.Release(middleware);
}
The default factory resolves from context.RequestServices — the request scope — which is
exactly why scoped constructor injection works.
You can supply your own IMiddlewareFactory if you need pooling or a custom container, though
that is rare.
The deeper detail — which should you use?¶
Conventional is the default, and what you will see in most codebases and documentation.
Choose IMiddleware when:
- The middleware has several scoped dependencies and method injection would be unwieldy
- You want the compiler to verify the shape rather than relying on a method name
- You want the middleware itself registered in DI so it can be replaced or decorated
Stay with conventional when:
- It has no scoped dependencies, or only one
- It runs on every request and you care about the extra allocation
- You want the simpler registration story
⚠️ The performance difference is real but small. Factory-based allocates one object per request plus a DI resolution. On a service handling thousands of requests per second that is measurable GC pressure (3.4); on a typical application it is irrelevant. Measure before deciding it matters.
⚠️ One genuine limitation: you cannot pass extra constructor arguments through
UseMiddleware<T>(args) with IMiddleware, because the container constructs it. Configuration
has to come through IOptions<T> — which is better practice anyway
(7.6).
Code¶
The same middleware written both ways, so the trade-off is visible.
Conventional — dependencies split across constructor and method:
public class TenantResolutionMiddleware(
RequestDelegate next,
ILogger<TenantResolutionMiddleware> logger) // singleton — constructor
{
public async Task InvokeAsync(
HttpContext context,
ITenantRepository tenants, // scoped — must go here
ITenantContext tenantContext) // scoped — and here
{
var host = context.Request.Host.Host;
var tenant = await tenants.FindByHostAsync(host, context.RequestAborted);
if (tenant is null)
{
logger.LogWarning("Unknown tenant host {Host}", host);
context.Response.StatusCode = StatusCodes.Status404NotFound;
return; // short-circuit
}
tenantContext.Current = tenant;
await next(context);
}
}
Factory-based — everything in the constructor, as normal:
public class TenantResolutionMiddleware(
ITenantRepository tenants,
ITenantContext tenantContext,
ILogger<TenantResolutionMiddleware> logger) : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var host = context.Request.Host.Host;
var tenant = await tenants.FindByHostAsync(host, context.RequestAborted);
if (tenant is null)
{
logger.LogWarning("Unknown tenant host {Host}", host);
context.Response.StatusCode = StatusCodes.Status404NotFound;
return;
}
tenantContext.Current = tenant;
await next(context);
}
}
builder.Services.AddScoped<TenantResolutionMiddleware>(); // required
// ...
app.UseMiddleware<TenantResolutionMiddleware>();
The second reads more like ordinary C#. With three dependencies, two of them scoped, that is worth the per-request allocation.
Testing¶
Both are testable, but IMiddleware is slightly cleaner because next is a parameter:
[Fact]
public async Task Returns_404_for_unknown_tenant()
{
var tenants = Substitute.For<ITenantRepository>();
tenants.FindByHostAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns((Tenant?)null);
var middleware = new TenantResolutionMiddleware(
tenants,
Substitute.For<ITenantContext>(),
NullLogger<TenantResolutionMiddleware>.Instance);
var context = new DefaultHttpContext();
context.Request.Host = new HostString("unknown.example.com");
var nextCalled = false;
await middleware.InvokeAsync(context, _ => { nextCalled = true; return Task.CompletedTask; });
Assert.Equal(404, context.Response.StatusCode);
Assert.False(nextCalled); // short-circuited, as intended
}
Interview questions¶
Q: What is IMiddleware and how does it differ from conventional middleware?
It is an interface with a single InvokeAsync method taking the context and the next delegate.
The difference is when the instance is created: conventional middleware is instantiated once at
startup and is effectively a singleton, whereas an IMiddleware implementation is resolved from
the DI container on every request. That means scoped services can go in the constructor like
normal, instead of having to be method-injected into InvokeAsync. It is also strongly typed,
so the compiler verifies the shape rather than the framework locating a method by name.
Q: Why can't you inject a DbContext into conventional middleware's constructor?
Because conventional middleware is created once when the pipeline is built, so the constructor
runs a single time and whatever it captures lives for the application's lifetime. A scoped
DbContext captured that way is shared across every concurrent request, which is both a
thread-safety problem and a memory leak as its change tracker grows. That is the captive
dependency problem. The conventional fix is to add the DbContext as a parameter on
InvokeAsync, which is resolved per request; the IMiddleware alternative sidesteps it
entirely.
Q: What is the catch with factory-based middleware?
You have to register it in the DI container yourself, usually with AddScoped. Conventional
middleware needs no registration, so it is easy to forget, and the failure appears on the first
request rather than at startup — an exception saying no service for that type has been
registered. There is also a small per-request cost, since you allocate an instance and perform
a container resolution for every request, which only matters at high throughput. And you cannot
pass extra constructor arguments through UseMiddleware, so configuration has to come through
IOptions.
Q: Which would you choose?
Conventional by default, because it needs no registration, allocates nothing per request, and is
what most codebases and documentation use. I would switch to IMiddleware when the middleware
has several scoped dependencies, since splitting them between the constructor and the method
reads badly, or when I want the middleware registered in DI so it can be decorated or replaced.
The performance difference is real but small enough that I would let readability decide unless
profiling said otherwise.
Traps ⚠️¶
- Forgetting to register it in DI. Fails on the first request, not at startup.
RequestDelegategoes in the method, not the constructor, unlike conventional middleware.- You cannot pass extra constructor arguments via
UseMiddleware<T>(args). UseIOptions. - One allocation and one DI resolution per request. Only matters at high throughput.
- Registering it as a singleton defeats the point — and reintroduces the captive dependency problem it was meant to solve.
- Mixing the two styles in one class does not work. A
RequestDelegateconstructor parameter plusIMiddlewarewill not behave as expected.
Related¶
- 5.5 Conventional middleware — the default alternative
- 5.7 Short-circuiting — the pattern used in the example
- 6.3 Service lifetimes — scoped vs singleton
- 6.4 Captive dependencies — what this avoids
- 6.5 Scopes — what
RequestServicesis - 7.6 Options pattern — configuring middleware