How to use a POCO object to access an array of options in the appsettings.json file (ASP.NET 5) How to use a POCO object to access an array of options in the appsettings.json file (ASP.NET 5) json json

How to use a POCO object to access an array of options in the appsettings.json file (ASP.NET 5)


Short Answer

I wondering if I am doing this wrong, or the Options Model doesn't support this type of behavior at this time?

You are doing one thing wrong. The Options Model does support arrays. You need NOT to initialize your array property with an array of size [1].

public Account[] Account { get; set; } = new Account[1];     // wrongpublic Account[] Account { get; set; }                       // right

Demo

Here is a sample, just for you, that you can find here on GitHub.

MyOptions.cs

namespace OptionsExample{    public class MyObj    {        public string Name { get; set; }    }    public class MyOptions    {        public string Option1 { get; set; }        public string[] Option2 { get; set; }        public MyObj[] MyObj { get; set; }    }}

Startup.cs

namespace OptionsExample{    using Microsoft.AspNet.Builder;    using Microsoft.AspNet.Hosting;    using Microsoft.AspNet.Http;    using Microsoft.Extensions.Configuration;    using Microsoft.Extensions.DependencyInjection;    using Microsoft.Extensions.OptionsModel;    using System.Linq;    public class Startup    {        public IConfigurationRoot Config { get; set; }        public Startup(IHostingEnvironment env)        {            Config = new ConfigurationBuilder().AddJsonFile("myoptions.json").Build();        }        public void ConfigureServices(IServiceCollection services)        {            services.AddOptions();            services.Configure<MyOptions>(Config);        }        public void Configure(IApplicationBuilder app,             IOptions<MyOptions> opts)        {            app.Run(async (context) =>            {                var message = string.Join(",", opts.Value.MyObj.Select(a => a.Name));                await context.Response.WriteAsync(message);            });        }    }}

myoptions.json

{    "option1": "option1val",    "option2": [        "option2val1",        "option2val2",        "option2val3"    ],    "MyObj": [        {            "Name": "MyObj1"        },        {            "Name": "MyObj2"        }    ]}

project.json dependencies

"dependencies": {    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final"}

Output

All options are present.