[英]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:我有一些 appsettings.json 配置文件:
{
"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:我尝试在我的 Startup.cs 文件中填充它:
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. MySettings
对象已创建,但未填充值。 ValueOne
and ValueTwo
are both null. ValueOne
和ValueTwo
均为空。 Why?为什么?
The Configuration extensions require explicit public getters and setters.配置扩展需要显式公共 getter 和 setter。 If they are implicit, or if either the get or set is private then the POCO object will not be mapped.
如果它们是隐式的,或者 get 或 set 是私有的,则不会映射 POCO 对象。 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.我使用以下 ConfigurationBuilder 和我的 SectionsCollection 类对其进行测试。
var baseConfig = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("mySettings.json")
.Build();
SectionsCollection sectionsCollection = baseConfig.Get<SectionsCollection>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.