How to add a list of specific object in a configuration file for a WorkerService

398 Views Asked by At

As far as what I understand:

appSettings is a dictionary of key value pair. But I can't find how to add a list of item as the value. Also, I would like to add my own object as the value if possible.

Is there a way to add a List of MyConfigObject (List<MyConfigObject>)into a config file? If yes, how? Should I use another section or should I use another type of config file (json, yaml) to have the simplest way to read/write settings?

2

There are 2 best solutions below

1
Ibrahim Hamaty On BEST ANSWER

Yes, you can, Like this:

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "MyConfigObject": [
    {
      "Prop1": "1",
      "Prop2": "2"
    },
    {
      "Prop1": "1",
      "Prop2": "2"
    }
  ]
}

MyConfigObject Class

public class MyConfigObject
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

In Startup, register the Configuration with the type MyConfigObject. Like this:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.Configure<List<MyConfigObject>>(Configuration.GetSection("MyConfigObject"));
    }

Now you can use it in any service or controller, like this:

public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly List<MyConfigObject> myConfig;
        public HomeController(IOptions<List<MyConfigObject>> myConfig, ILogger<HomeController> logger)
        {
            _logger = logger;
            this.myConfig = myConfig.Value;
        }

        public IActionResult Index()
        {
            return View();
        }
}
0
Eric Ouellet On

For the those who wonder how to get a JSON config section into an object without injection into a services:

var appFolder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);

    Configuration = new ConfigurationBuilder()
        .AddJsonFile(Path.Combine(appFolder, "appsettings.json"))
        .AddEnvironmentVariables()
        .Build();

    IConfigurationSection sectionMyConfigObject = Configuration.GetSection(nameof(MyConfigObject));
    var myConfigObject = sectionMyConfigObject.Get<List<MyConfigObject>>();

For file appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "MyConfigObject": [
    {
      "Prop1": "1",
      "Prop2": "2"
    },
    {
      "Prop1": "1",
      "Prop2": "2"
    }
  ]
}