I have two middleware in my asp.net core application. One middleware need to resister in service and other one don't need. Here is the code below:
1.
public class RequestMiddleware
{
private readonly RequestDelegate _next;
public RequestMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext, IWebHostEnvironment env)
{
try
{
await _next(httpContext);
}
catch (Exception ex)
{
// codes
}
}
}
// I use this middleware in startup
app.UseMiddleware<RequestMiddleware>();
2.
public class SampleMiddleware : IMiddleware
{
public Task InvokeAsync(HttpContext context, RequestDelegate next)
{
//codes
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<AppSampleLogsMiddleware>();
}
app.UseMiddleware<AppSampleLogsMiddleware>();
why second middleware need to register in ConfigureServices but first middleware don't need to register ? what is the different?
CodePudding user response:
The second way of creating middle is called Factory-based Middleware
UseMiddleware extension methods check if a middleware's registered type implements IMiddleware. If it does, the IMiddlewareFactory instance registered in the container is used to resolve the IMiddleware implementation instead of using the convention-based middleware activation logic. The middleware is registered as a scoped or transient service in the app's service container.
Benefits:
Activation per client request (injection of scoped services) Strong
typing of middleware
So, Because of implementing the IMiddleware
, Not only do you need to add this middleware to the request pipeline, But also need to register this middleware into DI containers.
Subtle difference has to do with scope. Factory-based middleware are transient and can receive scoped services via the constructor. You can follow this article to learn more.