Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I UseMiddleware<Type>(...) and pass in options?

Tags:

asp.net-core

I'm trying to understand how the ASP.NET Core pipeline works. I would like to use the StaticFileMiddleware and pass in some options.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    var staticFileOptions = new StaticFileOptions();
    app.UseMiddleware<Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware>(staticFileOptions);
}

When I run my application I get the following error

System.InvalidOperationException: A suitable constructor for type 'Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.
    at Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
    at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass3_0.<UseMiddleware>b__0(RequestDelegate next)
    at Microsoft.AspNetCore.Builder.Internal.ApplicationBuilder.Build()
    at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()

I understand that I can just use

app.UseStaticFiles(staticFileOptions);

But, as this is a learning exercise, I want to call it the other way.

like image 224
Kevin Brydon Avatar asked Oct 30 '22 16:10

Kevin Brydon


1 Answers

This is my approach to the same problem.

Just create new class with properties which you want to pass:

public class LoggingOption
{
    public bool ToLog { get; set; }
}

This is how to init

app.UseMiddleware<LoggingMiddleware>(Options.Create(new LoggingOption{ ToLog = true }));

And this is constructor

 public LoggingMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, IOptions<LoggingOption> options)
        {
            _next = next;
            _logger = loggerFactory.CreateLogger<LoggingMiddleware>();
            _toLog = options.Value.ToLog;
        }
like image 173
Madjarov Avatar answered Jan 02 '23 19:01

Madjarov