Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access configuration provider values in asp.net core startup

In my asp.net core 3.1 project I have setup a custom sql provider which is working great. In my Startup I want to load only the values from the SQLConfigurationProvider into a separate dictionary for use throughout my app. I can see that the configuration object contains a collection of providers as per below screenshot. However I cannot find a way to access only the SQLConfigurationProvider and get the subsequent values. Is this possible?

enter image description here

like image 738
OjM Avatar asked Oct 22 '25 04:10

OjM


1 Answers

What you can do is very simple. Once you build your ConfigurationRoot

IConfigurationRoot configRoot = config.Build();

What you can do is to enumerate to a List only the providers you want:

var providers = configRoot.Providers.Where(
    p => (p.GetType().Name == "AzureAppConfigurationProvider") ||
         (p.GetType().Name == "AzureKeyVaultConfigurationProvider")).ToList();

Then, recreate a new temporary ConfigurationRoot using only the selected providers:

var tempRoot = new ConfigurationRoot(new List<IConfigurationProvider>(providers));

Then, in order to get the values you can do the following:

tempRoot.AsEnumerable().ToDictionary(a => a.Key, a => a.Value)

This way you will get a Dictionary with the key/value pairs of the configuration.

Note: When you initialize a new ConfigurationRoot from the providers, the SDK triggers again the loading of the configuration which might introduce delays (especially if the configuration is retrieved from a cloud service). If you don't want something like that then you probably have to go with the solution suggested by Brando.

enter image description here

like image 61
Efthymios Kalyviotis Avatar answered Oct 23 '25 20:10

Efthymios Kalyviotis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!