0

this is my first question so please do not judge strictly
I'm trying to understand how Middleware receives parameters from Configure method in Startup class.
Here is the code of Middleware class:

public class LocationMiddleware
{
    private RequestDelegate next;
    private MessageOptions options;

    public LocationMiddleware(RequestDelegate nextDelegate,IOptions<MessageOptions> opts)
    {
        next = nextDelegate;
        options = opts.Value;
    }

    public async Task Invoke(HttpContext context)
    {
        if (context.Request.Path=="/location")
        {
            await context.Response.WriteAsync($"{options.CityName}, {options.CountryName}");
        }
        else
        {
            await next(context);
        }
    }
}

Constructor of this class takes 2 parameters RequestDelegate and IOptions<MessageOptions> But when calling a method UseMiddleware in Startup class no parameters are being sent in this line app.UseMiddleware<LocationMiddleware>();

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseMiddleware<LocationMiddleware>();

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("/", async context =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        });
    }

So my question is how middleware class receives this parameters?

1 Answer 1

0

Constructor of this class takes 2 parameters RequestDelegate and IOptions<MessageOptions> But when calling a method UseMiddleware in Startup class no parameters are being sent in this line app.UseMiddleware<LocationMiddleware>();

I assume that you added/registered MessageOptions to the service container, which will be resolved in your custom middleware.

services.Configure<MessageOptions>(Configuration.GetSection("MessageOptions"));

Besides, you can check the source code of UseMiddleware to know how it works.

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.