- Startup構(gòu)造函數(shù)
- ConfigureServices方法
- Configure方法
- 在ConfigureWebHostDefaults中直接配置服務(wù)和請求管道
ASP.NET Core一般使用Startup類來進行應(yīng)用的配置。在構(gòu)建應(yīng)用主機時指定Startup類,通常通過在主機生成器上調(diào)用WebHostBuilderExtensions.UseStartup 方法來指定 Startup類:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Startup類中可以包含以下方法:
- Startup構(gòu)造函數(shù)
- ConfigureServices方法,可選
- Configure方法
Startup構(gòu)造函數(shù)
在3.1中,使用泛型主機 (IHostBuilder) 時,Startup構(gòu)造函數(shù)中只能注入這三種類型的服務(wù):IWebHostEnvironment、IHostEnvironment、IConfiguration。
嘗試注入別的服務(wù)時會拋出InvalidOperationException異常。
System.InvalidOperationException: 'Unable to resolve service for type '***' while attempting to activate '_1_Startup.Startup'.'
因為主機啟動時,執(zhí)行順序為Startup構(gòu)造函數(shù) -> ConfigureServices方法 -> Configure 方法。在Startup構(gòu)造函數(shù)執(zhí)行時主機只提供了這三個服務(wù),別的服務(wù)需要在ConfigureServices方法中添加。然后到了Configure方法執(zhí)行的時候,就可以使用更多的服務(wù)類型了。
主機會調(diào)用ConfigureServices方法,將需要的服務(wù)以依賴注入的方式添加到服務(wù)容器,使其在Configure方法和整個應(yīng)用中可用。
ConfigureServices方法的參數(shù)中無法注入除IServiceCollection之外的服務(wù)。
具體使用時可以通過IServiceCollection的擴展方法為應(yīng)用配置各種功能。
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(
options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddRazorPages();
}
Configure 方法用于指定應(yīng)用響應(yīng) HTTP 請求的方式。 可通過將中間件組件添加到 IApplicationBuilder 實例來配置請求管道。 Configure 方法參數(shù)中的IApplicationBuilder不需要在服務(wù)容器中注冊就可使用,它已由主機創(chuàng)建好并直接傳遞給了Configure方法。
Configure方法由一系列的Use擴展方法組成:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}
每個Use擴展都在請求管道中添加了中間件。配置到請求管道中的中間件都會調(diào)用它之后的下一個中間件或者直接將管道短路。
在Configure方法參數(shù)中,可以根據(jù)自己的需要注入像IWebHostEnvironment, ILoggerFactory之類的服務(wù),或者是在ConfigureServices方法中添加到DI容器中的服務(wù)。
ASP.NET Core還提供了不使用Startup類而能夠配置服務(wù)和請求管道的方式。也可以在ConfigureWebHostDefaults上調(diào)用它提供的ConfigureServices和Configure方法。
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureServices((c, services) =>
{
services.AddControllers();
})
.Configure(app =>
{
var env = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
});
})
|