How to access IConfigurationRoot in startup on .net core 2?
Or you can inject it before initialization of the Startup
:
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
IConfigurationRoot configurationRoot = null;
return WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, builder) =>
{
configurationRoot = builder.Build();
})
.ConfigureServices(services =>
{
services.AddSingleton<IConfigurationRoot>(configurationRoot);
services.AddSingleton<IConfiguration>(configurationRoot);
})
.UseStartup<Startup>();
}
}
Thanks to Dealdiane's comment.
We can downcast the IConfiguration
:
public Startup(IConfiguration configuration)
{
Configuration = (IConfigurationRoot)configuration;
}
public IConfigurationRoot Configuration { get; }
I am still not sure, if this is the intended way, since IConfiguration
does not make any guarantees about IConfigurationRoot
.