Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to bind strongly typed arrays as configuration models in ASP.NET Core?

I have defined the following in my appsettings.json...

{
  "Environments": [
    {
      "Name": "One",
      "CloudServices": [
        "name1",
        "name2"
      ]
    },
    {
      "Name": "Two",
      "CloudServices": [
        "name3",
        "name4"
      ]
    }
  ]
}

...and the following strongly typed models:

public class EnvironmentModel
{
    public string Name { get; set; }
    public string[] CloudServices { get; set; }
}

public class EnvironmentsConfig
{
    public EnvironmentModel[] Environments { get; set; }
}

I was hoping I could bind this in my Startup like this:

services.Configure<EnvironmentsConfig>(Configuration.GetSection("Environments"));

However, when injected into my controller as IOptions<EnvironmentsConfig> the value is null. Is it possible to bind strongly typed arrays like this? If not, what is the recommended approach? The number of environments may differ between deployments hence my need for an array.

like image 907
Tom Troughton Avatar asked Oct 22 '25 04:10

Tom Troughton


1 Answers

The Environments section of your configuration contains an array of EnvironmentModel, not an EnvironmentsConfig. To fix it you just need to use the root of your config instead of a section. For example:

services.Configure<EnvironmentsConfig>(Configuration);
like image 131
DavidG Avatar answered Oct 23 '25 19:10

DavidG