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.


Comments
gravatar Juan Perez Monday, April 24, 2017
Hi Scott, nice post! I have a doubt, why is it necessary to inject `IOptions_AppConfig` in place of `AppConfig`? I mean, we could easily register a singleton of `AppConfig`, what is the benefit of `IOptions`?
gravatar Scott Monday, April 24, 2017
A layer of indirection, in case you want to change or refresh settings.
gravatar Juan Perez Monday, April 24, 2017
Thanks for your quick answer! It is very interesting, do you have an example of how to take advantage of it changing or refreshing the settings? (https://github.com/aspnet/Options is not so well documented)
gravatar Scott Allen Monday, April 24, 2017
Simplified in 1.1, see: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration#ioptionssnapshot
gravatar Juan Perez Tuesday, April 25, 2017
Thanks!
gravatar John Tuesday, April 25, 2017
Just make sure you have the casing of the json prop correct! https://github.com/aspnet/Configuration/issues/635
gravatar Juan Perez Wednesday, April 26, 2017
More information about "IOptions of T vs T for default injection": https://github.com/aspnet/Options/pull/116
Your Comment

My Pluralsight Courses

K.Scott Allen OdeToCode by K. Scott Allen
What JavaScript Developers Should Know About ECMAScript 2015
The Podcast!