Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass primitive data to asp.net core middleware

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

like image 391
ChrisCa Avatar asked Jun 12 '17 13:06

ChrisCa


People also ask

How does ASP.NET Core middleware work?

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.

Can we create custom middleware in .NET Core?

We can add middleware using app. UseMiddleware<MyMiddleware>() method of IApplicationBuilder also. Thus, we can add custom middleware in the ASP.NET Core application.

What is UseEndpoints in ASP.NET Core?

UseEndpoints adds endpoint execution to the middleware pipeline. It runs the delegate associated with the selected endpoint.


1 Answers

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.

like image 175
Ilya Chumakov Avatar answered Sep 28 '22 03:09

Ilya Chumakov