13

I have written a custom ConfigurationProvider with the entity framework. Since I also want to make it updateable during runtime, I have created a IWritableableOption.

I need to refresh the configuration after the update. This can be done via IConfigurationRoot.Reload.

However, how can I get the IConfigurationRoot in .net core 2?

What I have found, is that in previous versions the IConfigurationRoot was part of startup. In .net core 2 however, we have only the simpler type IConfiguration:

public Startup(IConfiguration configuration)
{
    // I tried to change this to IConfigurationRoot,
    // but this results in an unresolved dependency error
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

I also have found out, I can get my own instance using

WebHost.CreateDefaultBuilder(args).ConfigureAppConfiguration(context, builder) => {
    var configurationRoot = builder.build()
})

But I want to update the configuration used by Startup.

So how can I get the IConfigurationRoot used by Startup to inject it into my service collection?

Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111
  • 3
    The `configuration` parameter passed in `Startup` - isn't that an instance of `ConfigurationRoot` which implements both `IConfiguration` and `IConfigurationRoot`? – Dealdiane Feb 23 '18 at 03:08
  • 1
    Yeah, downcasting works, but I am not sure if this is the correct way of doing it @Dealdiane – Christian Gollhardt Feb 23 '18 at 03:25

2 Answers2

22

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.

Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111
4

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>();
    }
}
VahidN
  • 18,457
  • 8
  • 73
  • 117