从config.json使用services.Configure配置属性 [英] Configuring properties from config.json using services.Configure
问题描述
从StackOverflow的问题就在 mvc6使用IConfiguration href=\"http://stackoverflow.com/questions/27179370/using-iconfiguration-globally-in-mvc6\">全球范围内继。以接受的答案注释建议使用
Following on from a StackOverflow question regarding Using IConfiguration globally in mvc6. A comment to the accepted answer suggests using
services.Configure<SomeOptions>(Configuration);
现在能正常工作有以下code;
Now this works fine with the following code;
类
public class SomeOptions
{
public string MyOption { get; set; }
}
config.json
{
"MyOption": "OptionValue"
}
Startup.cs
public Startup(IHostingEnvironment env)
{
Configuration = new Configuration()
.AddJsonFile("config.json")
.AddEnvironmentVariables();
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<SomeOptions>(Configuration);
}
然而, config.json
文件没有任何真正的结构,我想它看起来更像;
However the config.json
file doesn't have any really structure, and I would like it to look more like;
{
"SomeOptions": {
"MyOption": "OptionValue"
}
}
然而,这不结合的类内的值。反正是有允许这样做?
However this does not bind the values within the class. Is there anyway to allow this?
推荐答案
如果你想修改 config.json
结构也需要改变您的类结构
If you want to change the config.json
structure you also need to change your class structure.
{
"SomeOptions": {
"MyOption": "OptionValue"
}
}
映射到像
public class SomeOptions
{
public List<MyOption> MyOptions { get; set; }
}
public class MyOption
{
public string OptionValue { get; set; }
}
这篇关于从config.json使用services.Configure配置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!