Configuring properties from config.json using services.Configure

怎甘沉沦 提交于 2019-12-24 02:43:27

问题


Following on from a StackOverflow question regarding Using IConfiguration globally in mvc6. A comment to the accepted answer suggests using

services.Configure<SomeOptions>(Configuration);

Now this works fine with the following code;

Class

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);
}

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?


回答1:


If you want to change the config.json structure you also need to change your class structure.

{
    "SomeOptions": {
        "MyOption": "OptionValue"
    }
}

maps to something like

public class SomeOptions
{
    public List<MyOption> MyOptions { get; set; }
}

public class MyOption
{
    public string OptionValue { get; set; }
}



回答2:


You can access specific value in config.json like:

Configuration.Get("SomeOptions:MyOption");

Which returns

"OptionValue"

So, your code will be

services.Configure<SomeOptions>(options => 
        options.MyOption = Configuration.Get("SomeOptions:MyOption"));



回答3:


services.Configure<SomeOptions>(Configuration.GetSubKey(nameof(SomeOptions)));

Should do it.



来源:https://stackoverflow.com/questions/27318935/configuring-properties-from-config-json-using-services-configure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!