Cristian Flaviu
Cristian Flaviu

Reputation: 325

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

Upvotes: 2

Views: 5239

Answers (2)

Guru Stron
Guru Stron

Reputation: 142193

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

Upvotes: 4

Aathreya
Aathreya

Reputation: 533

You can do this:

_config.GetConfigSection("AllowedGroups").GetChildren().ToList();

_config being derived from IConfiguration.

Upvotes: -2

Related Questions