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()

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)
    // ...


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

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
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
Comments are closed.