In ASP.NET Core, what shape must a convention-based middleware class have, and how do you add it to the request pipeline?
answer
- a shape, not an interface
- constructor takes RequestDelegate next
- public Invoke or InvokeAsync returning Task
- first parameter is HttpContext
- UseMiddleware<T>() behind a UseX extension
basics
~10 sA public constructor taking RequestDelegate next and a public Invoke or InvokeAsync method that returns Task and takes HttpContext first. Add it with app.UseMiddleware<T>(), usually wrapped in an IApplicationBuilder extension such as UseBrandResolution().
solid answer
~40 sConvention-based middleware implements no interface. `UseMiddleware<T>()` looks for exactly one public `Invoke` or `InvokeAsync` method that returns `Task` and whose first parameter is `HttpContext`; a missing or duplicated method, a non-`Task` return or a wrong first parameter throws `InvalidOperationException` when `UseMiddleware` is called. When the pipeline is built, it creates **one instance** with `ActivatorUtilities`, passing `next` plus any extra arguments you gave `UseMiddleware<T>(args)` and resolving the remaining constructor parameters from the root service provider. Extra parameters on `InvokeAsync` are resolved per request from `HttpContext.RequestServices`. By convention you expose it through an extension method on `IApplicationBuilder`, like the built-in `UseCors` or `UseStaticFiles`. An inline `app.Use((context, next) => ...)` lambda is enough for a few lines with no dependencies; a class pays off once there are dependencies, options or tests.
code
csharp · 25 linespublic sealed class BrandOptions
{
public Dictionary<string, string> Hosts { get; set; } = new();
public string DefaultBrand { get; set; } = "main";
}
public sealed class BrandResolutionMiddleware(RequestDelegate next, IOptions<BrandOptions> options)
{
public async Task InvokeAsync(HttpContext context)
{
var hosts = options.Value.Hosts;
context.Items["brand"] = hosts.TryGetValue(context.Request.Host.Host, out var brand)
? brand : options.Value.DefaultBrand;
await next(context);
}
}
public static class BrandResolutionExtensions
{
public static IApplicationBuilder UseBrandResolution(this IApplicationBuilder app)
=> app.UseMiddleware<BrandResolutionMiddleware>();
}
// Program.cs: builder.Services.Configure<BrandOptions>(builder.Configuration.GetSection("Brands"));
// app.UseBrandResolution();go deeper
Recall the four rules: RequestDelegate in the constructor, one public Invoke or InvokeAsync, a Task return, HttpContext first; then UseMiddleware<T> behind a UseX extension.
Explain when the instance is created, which provider resolves constructor versus InvokeAsync parameters, and what UseMiddleware validates at registration time.
Spot thread-safety and lifetime bugs that come from treating a convention class as per-request, and decide between lambda, class and IMiddleware.
Define how shared middleware is packaged across a team's services: UseX helpers, options binding and service checks that fail fast at startup.
## Three ways to write middleware ASP.NET Core gives you three ways to put your own code in the request pipeline: | Form | How it is added | Instances | Typical use | |---|---|---|---| | inline lambda | `app.Use(async (context, next) => ...)` | the lambda is built into the pipeline once | a few lines, no dependencies | | convention-based class | `app.UseMiddleware<T>()` | one per pipeline, created at startup | reusable middleware with singleton-safe dependencies | | `IMiddleware` class | `app.UseMiddleware<T>()` plus a DI registration | resolved from DI per request | middleware that needs scoped services in its constructor | This question is about the middle row, the form that built-in middleware such as `CorsMiddleware` and `StaticFileMiddleware` use. ## The convention, rule by rule A class is valid convention-based middleware when: 1. It has a **public constructor** whose parameters include a `RequestDelegate` (by convention named `next`). Other parameters are resolved from DI or taken from the arguments passed to `UseMiddleware<T>(args)`. 2. It has **exactly one** public instance method named `Invoke` or `InvokeAsync`. 3. That method returns **`Task`** (or a type assignable to `Task`). 4. Its **first parameter is `HttpContext`**. Further parameters are resolved from `HttpContext.RequestServices` on every request; `ref` and `out` parameters are rejected with `NotSupportedException`. `UseMiddlewareExtensions` checks rules 2 to 4 with reflection **at the moment `UseMiddleware<T>()` runs** in Program.cs, throwing `InvalidOperationException` with messages such as "No public 'Invoke' or 'InvokeAsync' method found", "Multiple public 'Invoke' or 'InvokeAsync' methods are available", or "The 'Invoke' or 'InvokeAsync' method's first argument must be of type 'HttpContext'". A `void` or `ValueTask` return fails the `Task` check. ## When the instance is created The constructor runs when the pipeline is **built**, which happens once as the host starts, not per request. `UseMiddleware` calls `ActivatorUtilities.CreateInstance(app.ApplicationServices, type, next, ...args)`, so constructor dependencies come from the **root** provider. That is why a convention class should only take singletons, `IOptions<T>`, `ILogger<T>` and plain values in its constructor; per-request services go on `InvokeAsync`. The instance is shared by all concurrent requests, so its fields must be safe to use from many threads at once. ## The UseX helper Built-in middleware is exposed through extension methods on `IApplicationBuilder` (`UseCors`, `UseStaticFiles`, `UseAuthentication`), and your own should be too: - the call site in Program.cs reads like the framework's own calls; - the helper can validate that the services it needs were registered and throw a clear error, as `UseAntiforgery` does; - it can accept settings and pass them to `UseMiddleware<T>(args)`, or bind an options object. ## A multi-brand storefront example A storefront host serves several brands from one deployment and picks the brand from the host name. The mapping is static configuration, so a singleton-safe `IOptions<BrandOptions>` in the constructor is fine: ```csharp public sealed class BrandResolutionMiddleware(RequestDelegate next, IOptions<BrandOptions> options) { public async Task InvokeAsync(HttpContext context) { var map = options.Value.Hosts; context.Items["brand"] = map.TryGetValue(context.Request.Host.Host, out var brand) ? brand : options.Value.DefaultBrand; await next(context); } } ``` Registering it is one line in Program.cs, `app.UseBrandResolution();`, behind the extension shown in the code example. If the brand lookup later needs the database, the database context must move to an `InvokeAsync` parameter, because a scoped service cannot be safely taken in this constructor. ## Lambda or class? - Keep an **inline lambda** for a handful of lines: a header, a quick guard, a log line. Use the `Use` overload that takes `(HttpContext, RequestDelegate)` and call `next(context)`. - Move to a **class** when the code needs dependencies, configuration, unit tests or reuse across apps. - Move to **`IMiddleware`** when the constructor itself needs scoped services or you want DI to own the instance's lifetime.
- What happens if the class declares both Invoke and InvokeAsync?`UseMiddleware<T>()` finds two candidate methods and throws `InvalidOperationException` ("Multiple public 'Invoke' or 'InvokeAsync' methods are available") as soon as that line runs in Program.cs. Keep exactly one.
- How do you pass a value that is only known in Program.cs to the middleware's constructor?Pass it to `UseMiddleware<T>(args)`: the arguments are handed to `ActivatorUtilities` after `next`, and DI fills the remaining constructor parameters. For anything configuration-shaped, binding an options class and taking `IOptions<T>` is usually cleaner.
- Why is a convention middleware's state shared between requests?Only one instance is created, when the pipeline is built, and every request calls `InvokeAsync` on it concurrently. Fields must therefore be immutable or thread-safe; per-request data belongs in locals, `HttpContext.Items` or a scoped service taken as an `InvokeAsync` parameter.
- A middleware class must implement IMiddleware to work with UseMiddleware<T>().
- ASP.NET Core creates a new convention middleware instance for every request.
- InvokeAsync may return void or ValueTask as long as it awaits next.
- Convention middleware classes must be registered with AddScoped before UseMiddleware<T>().
- Extra InvokeAsync parameters are resolved once, when the pipeline is built.