Search code examples
c#listapp-configappsettingsworker-service

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


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?


Solution

  • 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();
            }
    }