如主题所述,我不知道如何访问在CreateWebHostBuilder中设置的Configuration对象。
Code
:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.CustomExtension();
在代码示例中,我想通过CustomExtension方法访问Configuration
答案 0 :(得分:1)
对于IWebHostBuilder
,它用于配置WebHost
管道。
通常,如果要访问Configuration
,则需要将Configuration
对象传递给CustomExtension
,如:
var config = new ConfigurationBuilder()
.AddEnvironmentVariables()
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseStartup<Startup>();
以另一种方式,您可以尝试像UseConfiguration
来访问Configuration
对象,但是该代码仅在调用CreateWebHostBuilder(args).Build().Run()
时才运行。
public static class WebHostBuilderExtension
{
public static IWebHostBuilder CustomExtension(this IWebHostBuilder webHostBuilder)
{
return webHostBuilder.ConfigureServices(services => {
var config = services.BuildServiceProvider().GetRequiredService<IConfiguration>();
var connection = config.GetConnectionString("Default");
});
}
public static void CustomAction(IServiceCollection services)
{
var config = services.BuildServiceProvider().GetRequiredService<IConfiguration>();
var connection = config.GetConnectionString("Default");
}
}
用法:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.CustomExtension()
.ConfigureServices(services => WebHostBuilderExtension.CustomAction(services));