Let's suppose we have a middleware:
public class FooMiddleware
{
public FooMiddleware(RequestDelegate next, List<string> list)
{
_next = next;
}
}
Just pass a list to UseMiddleware call to resolve it per-middleware:
app.UseMiddleware<FooMiddleware>(new List<string>());
You could create a DTO and pass it:
public FooMiddleware(RequestDelegate next, Payload payload)
....
app.UseMiddleware<FooMiddleware>(new Payload());
Or register this DTO in DI container, it will be resolved in middleware:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<Payload>(new Payload());
}
In addition, DI container allows to resolve per-request dependencies:
public async Task Invoke(HttpContext httpContext, IMyScopedService svc)
{
svc.MyProperty = 1000;
await _next(httpContext);
}
Documentation:
Because middleware is constructed at app startup, not per-request,
scoped lifetime services used by middleware constructors are not shared with other dependency-injected types during each request. If
you must share a scoped service between your middleware and other
types, add these services to the Invoke method's signature. The
Invoke method can accept additional parameters that are populated by
dependency injection.