简体   繁体   中英

Can't get list of object from appsettings

I have app settings that look like this:

"Tenants": [
  {
    "Id": "00000000-0000-0000-0000-00000000000",
    "ConnectionString": "dbstring"
  },
  {
    "Id": "00000000-0000-0000-0000-00000000001",
    "ConnectionString": "dbstring"
  }
]

and an object that looks like this:

public class TenantSecrets
{
    public string ConnectionString { get; set; }
    public Guid Id { get; set; }
}

public class Tenants : List<TenantSecrets> { }

When I try to either configure them or bind them like so:

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

var tenants = new Tenants();
Configuration.Bind("Tenants", tenants);

The list is always empty, does anyone know why or how I can debug it? I can see the list in the appsettings configuration reader when I debug it, but the object never seems to map.

Edit: Good, you spotted this mistake, it happens it works perfectly. I don't want to write a useless answer so here is the version using the Options pattern .

Configure the Tenants class in the Startup.cs file (method ConfigureServices )

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

Then, inject the IOptions<Tenants> service in a controller constructor.

private readonly Tenants _tenants;

public HomeController(IOptions<Tenants> tenantOptions)
{
    _tenants = tenantOptions.Value;
}

好吧,我想通了,结果我用于 Id 的空 guid 比 guid 少一个 0,我现在知道配置到 poco 映射失败了,所以对于其他有问题的人,请检查您的数据符合数据类型

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM