Search code examples
c#.net-coreappsettings

Bind list of string from appsettings.json


I have the following list of string defined in my appSettings

 "AllowedGroups": [ "support", "admin", "dev" ] 

and I want to bind it to a class in the startup for dependency injection .

This is my model class

  public class AllowedGroups
    {
        public List<string> Groups { get; set; }
    }

This is how I tried to bind it.

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

I would like to keep the appsettings file in this format and I don't know how should I define de model class accordingly and how to bind it. I'm aware that he might expect to have "AllowedGroups":{Groups: [ "support", "admin", "dev" ]} with the current model


Solution

  • If you want to keep config structure you can just resolve everything "raw":

    var allowedGroups = Configuration.GetSection("AllowedGroups").Get<List<string>>();
    services.AddSingleton(new AllowedGroups {Groups = allowedGroups});
    

    Note that this will just register the AllowedGroups not the options as Configure does. To register options you can use next overload of Configure:

    services.Configure<AllowedGroups>(allowedGroups =>
        allowedGroups.Groups = Configuration.GetSection("AllowedGroups").Get<List<string>>());