I am trying to get settings from my config server and map it to my object.
However IConfiguration
is returning me a collection of Providers
and then I have to use the GetSection
or GetChildern
method to get configuration settings.
e.g.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MyConfigurations>(Configuration.GetSection("spring:cloud:config"));
}
The above gets me a particular section and am able to map it to my MyConfiguration
class properties.
However there are more sections I need to target. I don't want to do .GetSection
to get them one by one.
Is there anything I can use to get a collection from the required provider i.e. SteelToe
so that I can map it to the properties defined inside my config class?
You can create a mapping class for your configuration, like this:
public class ConfigSettings
{
public string ConfigSetting1 { get; set; }
public string ConfigSetting2 { get; set; }
public string ConfigSetting3 { get; set; }
public SubConfigSettings1 SubConfigSettings1 { get; set; }
}
public class SubConfigSettings1
{
public string SubConfigSetting1 { get; set; }
public string SubConfigSetting2 { get; set; }
}
and fetch them using,
var setting = Configuration.Get<ConfigSettings>();
EDIT:
if you have this steeltoe config
{
"spring": {
"cloud": {
"config": {
"uri": "http://localhost:8888"
}
}
},
"Logging": {
"IncludeScopes": true,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
},
"Console": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
}
You can define the ConfigSettings class like this.
public class ConfigSettings
{
public Spring spring { get; set; }
public Logging Logging { get; set; }
}
public class Spring
{
public Cloud cloud { get; set; }
}
public class Cloud
{
public Config config { get; set; }
}
public class Config
{
public string uri { get; set; }
}
public class Logging
{
public bool IncludeScopes { get; set; }
public Loglevel LogLevel { get; set; }
public Console Console { get; set; }
}
public class Console
{
public Loglevel LogLevel { get; set; }
}
public class Loglevel
{
public string Default { get; set; }
public string System { get; set; }
public string Microsoft { get; set; }
}
and use like this.
services.Configure<ConfigSettings>(Configuration);
and use the following to access uri section, for example.
var settings = Configuration.Get<ConfigSettings>();
string springCloudConfigUri = settings.spring.cloud.config.uri;
here, the Configuration is IConfiguration