Search code examples
c#asp.net-coreconfigurationmanager

ASP.NET IConfiguration, how to iterate or enumerate Providers


I am trying to write a test to verify that X providers are loaded in a certain scenario.

I can resolve the IConfiguration object, how can I tell how many IConfigurationProviders are in it?

In my startup, I use totally bog standard Configuration in my Program

IConfiguration configuration = null;
var builder = Host.CreateDefaultBuilder()
    .ConfigureServices((hostContext, services) =>
    {
        configuration = hostContext.Configuration;
        var startup = new Startup(hostContext.Configuration, hostContext.HostingEnvironment);
        //startup.ConfigureServices(services);
    })

    .ConfigureAppConfiguration((hostContext, config) =>
    {
        config.AddAzureKeyVaultsFromConfig();
    });

builder.Build();
return configuration;

When I'm debugging, I can see my list of Providers when I hover over configuration.

enter image description here

What I would want to do is see that there are 4 providers. I would also want to check and see what type the providers are.

If I use Enumerate() it just gives me a flattened list of all of the values and discards which provider it came from.


Solution

  • The object you have here is actually an IConfigurationRoot, and that happens to also implement IConfiguration. So if you treat it as such, you can access the Providers property. For example:

    IConfigurationRoot configuration = null;
    
    // snip the rest of your code
    
    var providerCount = configuration.Providers.Count();