I need to pass some data into a ASP NET CORE middleware
e.g. if this is a list of strings, do you use the same mechanism as passing in a service?
e.g. add it as a parameter to the Invoke method and register it with the DI?
If so, how do you do the registration for primitive types? e.g. a lsit of strings. does it have to be a named type or something like that?
Or can we pass the data in some other way?
thanks
Middleware is software that's assembled into an app pipeline to handle requests and responses. Each component: Chooses whether to pass the request to the next component in the pipeline. Can perform work before and after the next component in the pipeline.
We can add middleware using app. UseMiddleware<MyMiddleware>() method of IApplicationBuilder also. Thus, we can add custom middleware in the ASP.NET Core application.
UseEndpoints adds endpoint execution to the middleware pipeline. It runs the delegate associated with the selected endpoint.
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. TheInvoke
method can accept additional parameters that are populated by dependency injection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With