I'm trying to retrieve configuration inside my application.
I have passed the IConfiguration into the service class which needs to pull some settings.
The class looks a bit like this:
private IConfiguration _configuration;
public Config(IConfiguration configuration)
{
_configuration = configuration;
}
public POCO GetSettingsConfiguration()
{
var section = _configuration.GetSection("settings") as POCO;
return section;
}
In debug, I can see that _configuration does contain the settings but my "section" is simply returned as null.
I'm aware that I could try to set up the Poco to be created in the startup, and then injected as a dependency, but due to the setup, I'd rather do it in separate classes from the injected IConfiguration, if possible.
My appsettings.json has these values:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"settings": {
"Username": "user",
"Password": "password",
"Domain": "example.com",
"URL": "http://service.example.com"
}
}
My poco class looks like this:
public class POCO
{
public string URL { get; set; }
public string Username { get; set; }
public SecureString Password { get; set; }
public string Domain { get; set; }
}
You need to use:
var section = _configuration.GetSection("settings").Get<POCO>();
What's returned from GetSection
is just a dictionary of strings. You cannot cast that to your POCO class.
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