Configure 方法在 ASP.NET Core 3.1 中发挥着神奇的作用。
场景一
创建新项目时,框架会搭建以下方法签名:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
应用程序使用此签名并不奇怪,因为我可以假设 ASP.NET Core 框架期望签名保持原样。
场景二
第二个参数 IWebHostEnvironment 被移除:
public void Configure(IApplicationBuilder app)
应用程序有效。
场景三
在“ConfigureServices”方法中注入(inject)我的 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();
}
场景 4
注入(inject)了 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'.'
谁能解释一下方法调用实际上是如何由框架完成的,以及它如何能够解析少数类型,例如 ILogger 和 VegaDbContext 而不是 天气预报 Controller 。
最佳答案
它通过使用依赖注入(inject)基础设施来工作。 Configure
的参数是从 Web 主机的 ServiceProvider
中检索的。这里的关键字是“服务”——默认情况下, Controller 不作为服务添加到服务集合。
为了通过依赖注入(inject)访问 Controller ,您需要为 IMvcCoreBuilder
调用 AddControllersAsServices
扩展方法|或 IMvcBuilder
在您的 ConfigureServices
方法中。
services.AddControllers()
.AddControllersAsServices();
// or
services.AddControllersWithViews()
.AddControllersAsServices();
// or
services.AddMvc()
.AddControllersAsServices();
关于c# - asp.net core 中 'Configure' 方法有多少重载是可能的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62861048/