asp.net 核心中可以重载多少个 'Configure' 方法?

How many overloads of 'Configure' method are possible in asp.net core?

Configure 方法在 ASP.NET Core 3.1 中就像魔法一样工作。

场景一

创建新项目时,框架会搭建以下方法签名:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

应用程序使用此签名并不奇怪,因为我可以假设 ASP.NET 核心框架期望签名保持原样。

场景二

第二个参数 IWebHostEnvironment 被移除:

public void Configure(IApplicationBuilder app)

应用程序有效。

场景三

在 'ConfigureServices' 方法中注入我的 DbContext 添加到 IServiceCollection 以及记录器:

public void Configure(IApplicationBuilder app, ILogger<Startup> logger, VegaDbContext vegaDbContext)

令人惊讶的是,应用程序有效。看起来该框架足以解析添加到服务集合的类型。好兆头。

内联是 ConfigureServices 方法的实现:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<VegaDbContext>(options =>
            options.UseSqlServer(
                configuration.GetConnectionString("VegaDb")));
    services.AddControllers();
}

场景四

注入了 WeatherForecastController,我认为它是通过 services.AddControllers() 添加到 IServiceCollection:

public void Configure(IApplicationBuilder app, WeatherForecastController weatherForecastController)

应用程序无法运行。抛出以下异常:

System.Exception: 'Could not resolve a service of type 'Vega.Controllers.WeatherForecastController' for the parameter 'weatherForecastController' of method 'Configure' on type 'Vega.Startup'.'

谁能解释一下方法调用实际上是如何由框架完成的,以及它如何能够解析少数类型,如 ILoggerVegaDbContext 但不是 WeatherForecastController.

它通过使用依赖注入基础设施来工作。 Configure 的参数是从虚拟主机的 ServiceProvider 中检索的。这里的关键字是“服务”——默认情况下,控制器不会作为服务添加到服务集合中。

为了通过依赖注入访问控制器,您需要在 ConfigureServices 方法中为 IMvcCoreBuilder or IMvcBuilder 调用 AddControllersAsServices 扩展方法。

services.AddControllers()
        .AddControllersAsServices();
// or
services.AddControllersWithViews() 
        .AddControllersAsServices();
// or
services.AddMvc()
        .AddControllersAsServices();