Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access Configuration in a IWebHostBuilder extension

As the topic says, I can't figure out how to access the Configuration object set up in CreateWebHostBuilder.

Code:

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

In the code example I would like to access Configuration in the CustomExtension method

like image 435
SteinTheRuler Avatar asked Dec 04 '18 20:12

SteinTheRuler


1 Answers

For IWebHostBuilder, it is used to configure the WebHost pipeline.

For general way, if you want to access Configuration, you need to pass the Configuration object to CustomExtension like :

var config = new ConfigurationBuilder()
.AddEnvironmentVariables()
.Build();

var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseStartup<Startup>();

For another way, you could try like UseConfiguration to access Configuration object, but the code will run only when CreateWebHostBuilder(args).Build().Run() is called.

    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");
    }
}

Usage:

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .CustomExtension()
            .ConfigureServices(services => WebHostBuilderExtension.CustomAction(services));
like image 150
Edward Avatar answered Oct 21 '22 03:10

Edward