Search code examples
asp.net-coreasp.net-core-3.1asp.net-core-configuration

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


Solution

  • According to your description, I suggest you could firstly use Configuration.Providers to get the SQLConfigurationProvider.

    But the ConfigurationProvider's data property is protected, so we should write a extension method to get the value and set it into a directory.

    More details, you could refer to below codes:

    Create a extension class:

    public static class ConfigurationProviderExtensions
    {
        public static HashSet<string> GetFullKeyNames(this IConfigurationProvider provider, string rootKey, HashSet<string> initialKeys)
        {
            foreach (var key in provider.GetChildKeys(Enumerable.Empty<string>(), rootKey))
            {
                string surrogateKey = key;
                if (rootKey != null)
                {
                    surrogateKey = rootKey + ":" + key;
                }
    
                GetFullKeyNames(provider, surrogateKey, initialKeys);
    
                if (!initialKeys.Any(k => k.StartsWith(surrogateKey)))
                {
                    initialKeys.Add(surrogateKey);
                }
            }
    
            return initialKeys;
        }
    }
    

    Then you could add below codes to get the provider and get the value..

    // Replace the EnvironmentVariablesConfigurationProvider to your provider 
    var re =  ((ConfigurationRoot)Configuration).Providers.FirstOrDefault(x=>x.GetType() == typeof(EnvironmentVariablesConfigurationProvider));
    
    var directory = new Dictionary<string, string>();
    
    foreach (var key in re.GetFullKeyNames(null, new HashSet<string>()).OrderBy(p => p))
    {
        if (re.TryGet(key, out var value))
        {
            directory.Add(key, value);
        }
    }
    

    Result:

    enter image description here