我在appSettings中定义了以下字符串列表
"AllowedGroups": [ "support", "admin", "dev" ]
我想将其绑定到启动时的类以进行依赖项注入。
这是我的模特班
public class AllowedGroups
{
public List<string> Groups { get; set; }
}
这就是我试图绑定它的方式。
services.Configure<AllowedGroups>(Configuration.GetSection("AllowedGroups"));
我想以这种格式保留appsettings文件,但我不知道如何相应地定义模型类以及如何绑定它。我知道他可能期望"AllowedGroups":{Groups: [ "support", "admin", "dev" ]}
使用当前模型
如果您想保留配置结构,则可以解决所有“原始”问题:
var allowedGroups = Configuration.GetSection("AllowedGroups").Get<List<string>>();
services.AddSingleton(new AllowedGroups {Groups = allowedGroups});
请注意,这将只注册AllowedGroups
不选择的Configure
一样。要注册选项,可以使用下一个重载Configure
:
services.Configure<AllowedGroups>(allowedGroups =>
allowedGroups.Groups = Configuration.GetSection("AllowedGroups").Get<List<string>>());
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句