3
votes

I've been playing around a bit with Azure App Configuration.

Here's an example configruation:

var environmentVariable = Environment.GetEnvironmentVariable("AppConfigurationConnectionString");
var config =
    new ConfigurationBuilder()
        .AddAzureAppConfiguration(options =>
        {
            options.Connect(environmentVariable)
                .ConfigureKeyVault(kv =>
                {
                    kv.SetCredential(new DefaultAzureCredential());
                });
        })
        .Build();

services.AddSingleton<IConfiguration>(config);

Following this, I can inject an IConfiguration instance into my services and use _config["settingName"] to access config settings. This all works well and is really quite nice.

One thing that I don't know how to do is to map groups of related settings to a strongly typed object (that is, without having to do it all manually, which I could do, but... hoping there's a better way).

In conventional ASP.NET core configuration, I can group related settings settings as follows (i.e. in appsettings.json)

{
    "test": {
        "key1": "value1",
        "key2": "value2"
    }
}

using the IOptions pattern as follows:

services.Configure<Test>(config.GetSection("test"));

which allows me to inject a strongly-typed IOptions<Test> instance into my classes. IMO this is a bit nicer than a big flat indexer, where I use _config["key1"] to get config settings.

Is there an approach for Azure App Configruation to allow me to automatically configure strongly-typed config objects that can be injected into my classes?

TIA

1
map the settings in appsettings.json into a class?Ivan Yang
@IvanYang I'm thinking of moving my config settings out of appsettings.json to Azure App Configuration. Just trying to work out if I do this; how I can map groups of relate settings to strongly typed objects.Ryan.Bartsch

1 Answers

5
votes

.NET Core flattens objects in appsettings.json when it imports them into IConfiguration. For example, your test object becomes the following two keys in IConfiguration

_config["test:key1"]

_config["test:key2"]

This means that you can accomplish exactly what you want with Azure App Configuration by storing the settings in this flattened manner. The Azure App Configuration UI in the Azure portal has an import utility that will allow you to import an appsettings.json file and it does this importing for you.

Here is an example of the import utility in use: enter image description here

enter image description here

After you have the flattened object in Azure App Configuration the exact code you have will work.