为什么有些中间件需要注册`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个回答
4
投票

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

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

好处:

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

  • 中间件的类型

所以,因为实现了

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

细微的差别与范围有关。基于工厂的中间件是暂时的,可以通过构造函数接收作用域服务。您可以关注这篇文章了解更多。

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