简体   繁体   中英

Why don't the configuration values in my appsettings.json file map to my custom POCO object's fields via Configuration.GetSection().Get<MyObject>?

I have some appsettings.json config file:

{
  "PocoSettings": {
    "ValueOne": "Foo",
    "ValueTwo": "Bar"
  }
}

and a settings object that it should populate:

public class PocoSettings
{
    public string ValueOne;
    public string ValueTwo;
}

I try to populate it in my Startup.cs file:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddEnvironmentVariables();
    this.Configuration = builder.Build();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    var MySettings = this.Configuration.GetSection("PocoSettings").Get<PocoSettings>();

    // Inject MySettings into your DI container of choice here.
}

The MySettings object is created, but the values are not populated. ValueOne and ValueTwo are both null. Why?

The Configuration extensions require explicit public getters and setters. If they are implicit, or if either the get or set is private then the POCO object will not be mapped. The class should read:

public class PocoSettings
{
    public string ValueOne { get; set; }
    public string ValueTwo { get; set; }
}

Try this:

PocoSettings MySettings = this.Configuration.Get<PocoSettings>();

I test it using the follow ConfigurationBuilder and my SectionsCollection class.

var baseConfig = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("mySettings.json")
        .Build();
SectionsCollection sectionsCollection = baseConfig.Get<SectionsCollection>();

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