In ASP.NET Core, how does middleware implementing IMiddleware differ from convention-based middleware in activation, DI registration and lifetime?
answer
- InvokeAsync(HttpContext, RequestDelegate next)
- IMiddlewareFactory, registered scoped
- resolved per request from RequestServices
- must be registered: AddScoped or AddTransient
- UseMiddleware args throw NotSupportedException
basics
~20 sAn IMiddleware class is resolved per request by IMiddlewareFactory from the request scope, so it must be registered in DI and may take scoped services in its constructor. Convention middleware is created once at startup and needs no registration.
solid answer
~40 s`IMiddleware` has one method, `Task InvokeAsync(HttpContext context, RequestDelegate next)`. `UseMiddleware<T>()` detects the interface and, on every request, asks the scoped `IMiddlewareFactory` to create the instance; the default `MiddlewareFactory` simply calls `GetRequiredService` on the request's provider, invokes it, then calls `Release`, which does nothing because the container owns the lifetime. So you must register the class, normally with `AddScoped` or `AddTransient`; forgetting it surfaces on the first request as `InvalidOperationException` ("No service for type ... has been registered"), not at startup. Because it comes from the request scope, its constructor can take a scoped `DbContext`. You cannot pass arguments through `UseMiddleware<T>(args)`: that throws `NotSupportedException`. The cost is a DI resolution per request in exchange for strong typing and DI-owned lifetime.
code
csharp · 22 linespublic sealed class TenantResolutionMiddleware(StorefrontDbContext db, ITenantContext tenant) : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var brand = await db.Brands.AsNoTracking()
.SingleOrDefaultAsync(b => b.Host == context.Request.Host.Host, context.RequestAborted);
if (brand is null)
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
return;
}
tenant.Set(brand.Id, brand.Name);
await next(context);
}
}
// Program.cs
builder.Services.AddScoped<TenantResolutionMiddleware>(); // required for IMiddleware
// ...
app.UseMiddleware<TenantResolutionMiddleware>(); // no extra args allowedgo deeper
Know that IMiddleware is the interface-based alternative and that its class must be registered in DI.
Explain per-request activation through IMiddlewareFactory, why scoped constructor dependencies are safe there, and the two failure modes: missing registration and explicit args.
Weigh per-request resolution cost against clearer DI-shaped code, pick the registration lifetime, and make sure a missing registration is caught by tests rather than the first user.
Decide a house style for custom middleware across services, and when a custom IMiddlewareFactory is justified by a container strategy.
## The interface `IMiddleware` lives in `Microsoft.AspNetCore.Http` and declares a single method: ```csharp Task InvokeAsync(HttpContext context, RequestDelegate next); ``` Unlike convention-based middleware, `next` is a **method parameter**, not a constructor parameter, and the signature is fixed: no extra per-request parameters on `InvokeAsync`. Per-request services go in the constructor instead, which is the point of the interface. ## How UseMiddleware activates it `UseMiddleware<T>()` checks whether `T` implements `IMiddleware`. If it does, it skips the reflection-based convention binder and inserts a small delegate that runs on **every request**: 1. Resolve `IMiddlewareFactory` from `context.RequestServices`. The host registers the default `MiddlewareFactory` as **scoped**, so it wraps the request's service provider. 2. Call `factory.Create(typeof(T))`. The default implementation is `GetRequiredService(middlewareType) as IMiddleware`. 3. Await `middleware.InvokeAsync(context, next)`. 4. In a `finally`, call `factory.Release(middleware)`. The default implementation does nothing: the container that created the instance owns its lifetime and disposes it with the scope if it is scoped or transient. Two error paths follow from that code: - **Not registered**: `GetRequiredService` throws `InvalidOperationException` ("No service for type 'TenantResolutionMiddleware' has been registered.") on the first request that reaches it. The app starts normally, which makes this easy to miss without an integration test. - **Arguments passed**: `app.UseMiddleware<TenantResolutionMiddleware>("main")` throws `NotSupportedException` ("Types that implement 'IMiddleware' do not support explicit arguments.") when that line runs, because the container, not the caller, builds the instance. ## Side by side | | Convention-based | `IMiddleware` | |---|---|---| | Contract | public `Invoke`/`InvokeAsync`, found by reflection | interface method `InvokeAsync(HttpContext, RequestDelegate)` | | DI registration | none | required, typically `AddScoped<T>()` or `AddTransient<T>()` | | Created | once, when the pipeline is built | per request, by `IMiddlewareFactory` | | Constructor dependencies | root provider: singletons and options only | request scope: scoped services allowed | | Per-request services | extra `InvokeAsync` parameters | constructor | | `UseMiddleware<T>(args)` | supported | `NotSupportedException` | | Per-request cost | a method call, plus resolving any extra `InvokeAsync` parameters | a DI resolution of the middleware and its dependencies, plus the call | ## Choosing the lifetime of the registration - **Scoped**: one instance per request, sharing the request's scoped dependencies; the common choice. - **Transient**: a new instance per resolution; almost the same here, since the factory resolves it once per request for each place it appears in the pipeline (scoped would share one instance between two positions). - **Singleton**: legal, but then constructor dependencies must be singletons too; a scoped dependency becomes a captive one, and scope validation in Development rejects it. ## The storefront tenant resolver as IMiddleware In the multi-brand storefront host, tenant resolution needs the scoped `StorefrontDbContext` and a scoped `ITenantContext`. With `IMiddleware` both arrive through the constructor, the class is registered with `AddScoped`, and Program.cs still calls `app.UseMiddleware<TenantResolutionMiddleware>()` (or a `UseTenantResolution()` helper). The code reads like any other DI-constructed service, which can be clearer than a long `InvokeAsync` parameter list. ## Performance and testing trade-offs Convention middleware pays its activation cost once; `IMiddleware` pays a DI resolution, and the construction of the instance and its dependencies, on every request that reaches it. For a tenant resolver that already opens a database query, that overhead is negligible; for a hot header-stamping middleware on every static file, it is mostly overhead, and a convention class with `InvokeAsync` parameters does the same job. Testing can be simpler with `IMiddleware`. A test can construct the class directly with fakes for its constructor dependencies, then call `InvokeAsync(context, next)` with a stub `next`. A convention class can be tested the same way, but its per-request services arrive as method parameters, so every test call has to pass them explicitly. ## When to replace IMiddlewareFactory The factory is the extension point for containers or frameworks that want to own middleware creation themselves: a custom `IMiddlewareFactory` registered in DI can create instances from another container and dispose them in `Release`. Most applications never replace it.
- What happens if you forget the AddScoped registration for an IMiddleware class?The app starts, because nothing resolves the class during pipeline construction. The first request that reaches it fails: the default `MiddlewareFactory` calls `GetRequiredService`, which throws `InvalidOperationException` saying no service for the type has been registered.
- Can an IMiddleware class receive constructor arguments through UseMiddleware<T>(args)?No. `UseMiddleware` throws `NotSupportedException` when arguments are passed for a type implementing `IMiddleware`, because the container builds the instance. Supply settings through DI instead, for example `IOptions<T>`.
- Why would anyone implement a custom IMiddlewareFactory?To let something other than the built-in container create and release middleware instances, for example a third-party container that must also dispose them. `Create` returns the instance and `Release` is called after `InvokeAsync`, even when it throws.
- IMiddleware instances are created once at startup, just like convention middleware.
- IMiddleware types need no DI registration because UseMiddleware<T>() constructs them.
- A missing IMiddleware registration makes the app fail at startup.
- IMiddleware's InvokeAsync can take extra per-request services as parameters.
- UseMiddleware<T>(args) passes the args to an IMiddleware constructor.