Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access IConfigurationRoot in startup on .net core 2?

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?

like image 513
Christian Gollhardt Avatar asked Feb 23 '18 00:02

Christian Gollhardt


People also ask

How do I get AppSettings JSON value in startup CS?

In order to add AppSettings. json file, right click on the Project in Solution Explorer. Then click Add, then New Item and then choose App Settings File option (shown below) and click Add button. Once the File is created, it will have a DefaultConnection, below that a new AppSettings entry is added.

How do I get IConfiguration on my controller?

Using IConfiguration The IConfiguration is available in the dependency injection (DI) container, so you can directly access JSON properties by simply injecting IConfiguration in the constructor of a controller or class. It represents a set of key/value application configuration properties.

How do you inject IConfiguration in net core 6?

You could add the IConfiguration instance to the service collection as a singleton object in ConfigureServices : public void ConfigureServices(IServiceCollection service) { services. AddSingleton<IConfiguration>(Configuration); //... }


1 Answers

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.

like image 115
Christian Gollhardt Avatar answered Oct 10 '22 05:10

Christian Gollhardt