Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IConfiguration.GetSection() as Properties returns null

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; }
}
like image 952
PeaceDealer Avatar asked Jan 02 '23 08:01

PeaceDealer


1 Answers

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.

like image 81
Chris Pratt Avatar answered Jan 12 '23 22:01

Chris Pratt