Reputation: 3225
I'm having a problem getting data from my appsettings.json
.
The file looks like:
"Integrations": {
"System01": {
"Host": "failover://(tcp://localhost:61616)?transport.timeout=2000",
"User": "admin",
"Password": "admin"
},
"System02": {
"Host": "failover://(tcp://localhost:61616)?transport.timeout=2000",
"User": "admin",
"Password": "admin"
},
}
I have the following DTO:
public class IntegrationsConfigurationDto
{
public string Host { get; set; }
public string User { get; set; }
public string Password { get; set; }
}
When trying to read it like:
var config = _configuration.GetValue<IntegrationsConfigurationDto>("Integrations:System01");
I get null
. But if I do:
var config = new IntegrationsConfigurationDto();
_config.Bind("Integrations:System01", config);
I get the values correctly in my config
variable.
Why does that happen? How can I use GetValue<T>
in this scenario?
Thanks in advance.
Upvotes: 8
Views: 10201
Reputation: 93153
GetValue
only works for simple values, such as string
, int
, etc - it doesn't traverse the hierarchy of nested configuration.
Reference: Configuration in ASP.NET Core: GetValue
ConfigurationBinder.GetValue<T>
extracts a value from configuration with a specified key and converts it to the specified type. An overload permits you to provide a default value if the key isn't found.
Instead of using Bind
, use the following to avoid having to create your own instance of IntegrationsConfigurationDto
:
var config = _configuration.GetSection("Integrations:System01")
.Get<IntegrationsConfigurationDto>();
Reference: Configuration in ASP.NET Core: Bind to an object graph
ConfigurationBinder.Get<T>
binds and returns the specified type.Get<T>
is more convenient than usingBind
.
Upvotes: 25