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.
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;
}
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