6

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

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.