Home > other >  How to map a sub-array in Options into a Dictionary
How to map a sub-array in Options into a Dictionary

Time:12-29

My options in appsettings.json look like this:

  "ApplicationSettings": {
    "Value1": "abc",
    "Value2": 5,
    ...
    "MaxDOP": [
      {
        "Region": "A",
        "ThreadCount": 20
      },
      {
        "Region": "B",
        "ThreadCount": 30
      },
      ...
    ]
  }

I inject it as usual:

services.Configure<Models.AppConfigModel>(Configuration.GetSection("ApplicationSettings"));

The problem for me is how to map the MaxDOP array so that it will maintain the up-to-date sync via IOptionsMonitor<>. debug info


Solution 2: Include dictionary into main settings POCO

Change the signature of MaxDOP from list to dictionary:

appsettings.json:

"ApplicationSettings": {
    "Value1": "abc",
    "Value2": 5,
    "MaxDOP": {
      "A": {
        "ThreadCount": 20
      },
      "B": {
        "ThreadCount": 30
      }
    }
  }

Poco classes:

public class ApplicationSettings
{
    public string Value1 { get; set; }
    public int Value2 { get; set; }
    public Dictionary<string, Dop> MaxDOP { get; set; }
}

public class Dop
{
    public int ThreadCount { get; set; }
}

Configuring:

services.Configure<ApplicationSettings>(Configuration.GetSection("ApplicationSettings"));

Usage:

public HomeController(IOptionsMonitor<ApplicationSettings> monitor)
{
    _monitor = monitor;
    ApplicationSettings a = _monitor.CurrentValue;
}

debug info

  • Related