简体   繁体   中英

Asp.Net Core 3.1 Multiple dependent custom configuration providers

To begin with a custom configuration provider, we would add this code to Program.CreateHostBuilder:

.ConfigureAppConfiguration((builderContext, config) =>
                {
                    config.AddMyConfiguration(options =>
                    {
                        options.ConnectionString = "Data Source=sqlite.db";
                        options.Query = @"SELECT Key, Value FROM SYS_CONFIGS";
                    });
                });

(just an example, not what I'm actually doing). But what if we needed to add another custom config provider, and the request for the remote data depended on values from source number one already being available? So something like this, appearing in Program.CreateHostBuilder in addition to the above:

.ConfigureAppConfiguration((builderContext, config) =>
                {
                    config.AddMySecondConfiguration(options =>
                    {
                        options.ConnectionString = "<some value received from first custom config>";
                        options.Query = "<some value received from first custom config>";
                    });
                });

I think you need to build the configurationBuilder in your second configuration provider.

Try this:

.ConfigureAppConfiguration((context, configurationBuilder) =>
{
    configurationBuilder.AddInMemoryCollection(new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("first", "value")
    });

    configurationBuilder.AddInMemoryCollection(new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("second", configurationBuilder.Build().GetValue<string>("first"))
    });
    
    var test = configurationBuilder.Build().GetValue<string>("second"); // "value"
})

But why do you want to do it like this? Wouldn't it be better to handle all of this logic in one custom configuration provider? Fetch the data you need then act on it accordingly? Could you please explain a bit more of what problem you are trying to solve here?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM