Setting properties from config.json using services.Configure

Further from the StackOverflow question regarding Using IConfiguration worldwide in mvc6 . Commentary on accepted answer involves 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 config.json not have any real structure, and I would like it to look more like:

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

However, this does not bind the values ​​inside the class. Is there any way to resolve this?

+2
source share
3 answers

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

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

displays something like

 public class SomeOptions { public List<MyOption> MyOptions { get; set; } } public class MyOption { public string OptionValue { get; set; } } 
+2
source

You can access a specific value in config.json, for example:

 Configuration.Get("SomeOptions:MyOption"); 

What returns

 "OptionValue" 

So your code will be

 services.Configure<SomeOptions>(options => options.MyOption = Configuration.Get("SomeOptions:MyOption")); 
+1
source
 services.Configure<SomeOptions>(Configuration.GetSubKey(nameof(SomeOptions))); 

Gotta do it.

0
source

All Articles