【问题标题】:Binding options inside other options services.Configure<>()在其他选项 services.Configure<>() 中绑定选项
【发布时间】:2021-12-22 21:32:18
【问题描述】:

假设我在 appsettings.json 中有以下设置:

  {
  "OtherSettings" : {
    "id" : 3
  },
  
  "Needed" : {
    "Database" : {
      "ConnectionString" : "abc123"
    },

    "Interval" : {
      "is_active" = true,
      "in_seconds" = "15" 
    }
  } 
}

对于数据库部分,我有一个类是 DatabaseSettings,属性为 ConnectionString

对于间隔部分,我有 IntervalSettings 类。

如果我想将 Needed 中的所有这些设置绑定到类 NeededSettings,我需要什么属性以及如何将 Database 类的选项与依赖注入绑定?目前我正在这样做:

services.Configure<DatabaseSettings>Configuration.GetSection("Needed:Database"));
services.Configure<IntervalSettings>(Configuration.GetSection("Needed:Interval"));

所以我用 2 行来做这件事,但我想用 1 行来做,并将所有设置绑定到新类 NeededSettings

【问题讨论】:

    标签: c# asp.net .net configuration


    【解决方案1】:

    只需删除这两行并添加:

    services.Configure<NeededSettings>(Configuration.GetSection("Needed"));
    

    并在您使用DatabaseSettingsIntervalSetttings 的所有地方使用NeededSettings

    编辑:

    public class NeededSettings{
        public DatabaseSettings Database {get;set;}
        public IntervalSettings Interval {get;set;}
    }
    
    

    【讨论】:

    • 但是这个NeededSettings 类有什么属性呢?
    • @schweppes0x 查看更新版本的评论。
    猜你喜欢
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多