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
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With