如何在IWebHostBuilder扩展中访问配置

时间:2018-12-04 20:09:21

标签: c# asp.net-core

如主题所述,我不知道如何访问在CreateWebHostBuilder中设置的Configuration对象。

Code

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .CustomExtension();

在代码示例中,我想通过CustomExtension方法访问Configuration

1 个答案:

答案 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));