为什么有些中间件需要注册到 `ConfigureServices` 而有些则不需要?

问题描述 投票:0回答:1

我的 ASP.NET Core 应用程序中有两个中间件。一个需要在

ConfigureServcies
注册,而另一个则不需要。

例如:

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)
            {
                // ... code ...
            }
        }
   }

// I use this middleware in startup
app.UseMiddleware<RequestMiddleware>();
  1. public class SampleMiddleware : IMiddleware 
    {
    
        public Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            // ... code ...
        }
    } 
    
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<AppSampleLogsMiddleware>();
    }
    app.UseMiddleware<AppSampleLogsMiddleware>();
    

为什么第二个需要注册,而不是第一个?它们有何不同?

asp.net asp.net-core middleware
1个回答
5
投票

第二种创建中间件的方式称为基于工厂的中间件

UseMiddleware
扩展方法检查中间件的注册类型是否实现
IMiddleware
。如果是,则使用容器中注册的
IMiddlewareFactory
实例来解析
IMiddleware
实现,而不是使用基于约定的中间件激活逻辑。中间件在应用程序的服务容器中注册为作用域或瞬态服务。

好处:

  • 根据客户端请求激活(注入范围服务)强

  • 中间件的类型

因此,由于实现了

IMiddleware
,您不仅需要将此中间件添加到请求管道中,还需要将其注册到DI容器中。

这种微妙的差异与范围有关。基于工厂的中间件是暂时的,可以通过构造函数接收作用域服务。请参阅为 .NET Core 创建传统的基于工厂的中间件帖子以了解更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.