The recommended approach would be to avoid doing so and rather use IOptions<TOptions>
and IServiceCollection.Configure<TOptions>
.
That said, this is still pretty straightforward to make IConfigurationRoot
available application wide.
In the Startup.cs constructor you should have the following code to build the configuration,
Configuration = builder.Build();
Here Configuration
is an instance of IConfigurationRoot
,
And add this instance as a Singleton to the service collection in ConfigureServices method , Startup.cs ,
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfigurationRoot>(provider => Configuration);
For example, you can now access the configuration in a Controller/Service
public MyController(IConfigurationRoot config){
var setting1= config.GetValue<string>("Setting1")
}