Pretty standard procedure for manual configuration wire up
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
Then I call
var procSettings = builder.GetSection(ProcessSettings.SectionName).Get<ProcessSettings>();
Some data does not load. And I know why - some properties don't match to JSON attributes. I tried to decorate it with [JsonPropertyName("captureTrace")]
thinking that microsoft would use its own binding (System.Text.Json.Serialization
). But no! Do they really use property name and not checking the attributes? Basically, is there a way to do it - have property name different from the JSON property name?
Max I found
.Get<ProcessSettings>(x => new BinderOptions().BindNonPublicProperties = true);
Also, in my case I have the nested class, where other classes contain groups of properties within it.
You can decorate the property with [ConfigurationKeyName]
For example:
public record class ProcessSettings
{
[ConfigurationKeyName("any name")]
public string CaptureTrace { get; set; }
}
appsettings.json:
{
"MyProcessSettings": {
"any name": "AnyValue"
}
}
test:
using Microsoft.Extensions.Configuration;
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var setting = builder
.GetSection("MyProcessSettings")
.Get<ProcessSettings>();
Console.WriteLine(setting);
output:
ProcessSettings { CaptureTrace = AnyValue }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With