且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 .Net 5 (Asp.Net) 中的 appsettings.json 映射多级设置

更新时间:2023-02-14 15:03:33

我在这里假设您在谈论绑定(应用设置文件到单个对象?)如果您可以接受一些额外的代码,那么这可以满足您想要实现的目标.

IConfigurationRoot configRoot = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();设置 settingsRoot = new Settings();//带有 appsettings 结构的自定义 POCO((IConfiguration)configRoot).Bind(settingsRoot);公开课设置{公共日志记录 { get;放;}公共字符串 AllowedHosts { 获取;放;}}公共类 LogLevel{公共字符串默认{获取;放;}公共字符串 Microsoft { get;放;}}

如果您只想设置单个节点/部分的层次结构,您可以简单地执行一个 ((IConfiguration)config.GetSection("SectionName")).Bind(myObject)>

无论哪种方式,config.Bind(object) 都是这里的魔法部分.

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://docs.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 sigle object if it is possible.

Any suggestion?

Am assuming here you're talking about binding (app settings file to a single object?) If you're okay with bit of extra code then this could work for what you want to achieve.

IConfigurationRoot configRoot = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
Settings settingsRoot = new Settings(); // custom POCO with appsettings structure
((IConfiguration)configRoot).Bind(settingsRoot);

public class Settings
{
    public Logging Logging { get; set; }

    public string AllowedHosts { get; set; }
}
public class LogLevel
{
    public string Default { get; set; }
    public string Microsoft { get; set; }
}

If you're only trying to setup a single node/section's hierarchy you can simply do a ((IConfiguration)config.GetSection("SectionName")).Bind(myObject)

Either way config.Bind(object) is the magic bit here.