I am migrating an Asp.Net MVC application to .Net5. I had a static class that served as a façade for the settings in web.config. My Setting class exposed static properties, each one of a class representing settings groups, for example:
public static class MySettings
{
public static class MainDB
{
public static string ConnectionString
{
get
{
// Code to retrieve the actual values
return "";
}
}
}
public static class ExternalApi
{
public static string Uri
{
get
{ // Code to retrieve the actual values
return "";
}
}
}
public static class OtherSettings
{
// ...
}
}
In .Net Core 5 (actually, since .Net Core 2) we use POCO's tyo read settings as depicted in https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-5.0
Is there any way to map all my settings to one single object, for example, for appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Settings": {
"MainDB": {
"ConnectionString": "whatever needed to access the db"
},
"ExtrenaAPI" {
"Uri": "https://whatever.api.com",
"Key": "mysupersecretkey",
"Secret": "mysupersecret-uh-secret"
}
}
}
Classes:
public class MainDB
{
public string ConnectionString { get; set; }
}
public class ExternalApi
{
public string Uri { get; set; }
public string Key { get; set; }
public string Secret { get; set; }
}
public class Settings
{
public MainDB MainDB { get; set; }
`public ExternalApi ExternalApi { get; set; }
}
Configuration (in Startup.cs):
services.Configure<Settings>(Configuration.GetSection("Settings"));
(Yes, I know I can do services.Configure<MainDB>(Configuration.GetSection("Settings:MainDB")); and services.Configure<ExternalApi>(Configuration.GetSection("Settings:ExternalApi")); but I'd like to get all the settings in one single object if it is possible.
Any suggestion?