OdeToCode IC Logo

ASP.NET Configuration Options Will Understand Arrays

Monday, April 24, 2017

Continuing on topics from code reviews.

Last year I saw some C# code working very hard to process an application config file like the following:

{
  "Storage": {
    "Timeout":  "25", 
    "Blobs": [
      {
        "Name": "Primary",
        "Url": "foo.com"

      },
      {
        "Name": "Secondary",
        "Url": "bar.com"

      }
    ]
  }
}

Fortunately, the Options framework in ASP.NET Core understands how to map this JSON into C#, including the Blobs array. All we need are some plain classes that follow the structure of the JSON.

public class AppConfig
{
    public Storage Storage { get; set; }            
}

public class Storage
{
    public int TimeOut { get; set; }
    public BlobSettings[] Blobs { get; set; }
}

public class BlobSettings
{
    public string Name { get; set; }
    public string Url { get; set; }
}

Then, we setup our IConfiguration for the application.

var config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .Build();

And once you’ve brought in the Microsoft.Extensions.Options package, you can configure the IOptions service and make AppConfig available.

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddOptions();
    services.Configure<AppConfig>(config);
}

With everything in place, you can inject IOptions<AppConfig> anywhere in the application, and the object will have the settings from the configuration file.