IConfiguration.GetSection() as Properties returns null

6.3k Views Asked by At

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

There are 2 best solutions below

9
On BEST ANSWER

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.

0
On

IConfiguration and IConfigurationSection have an extension method Bind for this purpose:

var poco = new POCO();
_configuration.GetSection("settings").Bind(poco);

Or just Get

var poco = _configuration.GetSection("settings").Get(typeof(POCO));

Or generic Get

var poco = _configuration.GetSection("settings").Get<POCO>();