【问题标题】:Read appsettings.json into object that has an interface defined将 appsettings.json 读入定义了接口的对象中
【发布时间】:2021-07-04 03:52:56
【问题描述】:

我需要将 appsettings.json 中的自定义设置读取到定义了自定义接口的 POCO 对象中。此代码有效 - 但有更好的方法吗?也许类似于通过 services.Configure 和 IOptions 读取选项?不幸的是,无法使用 IOptions,因为我正在调用另一个库,该库需要一个实现“IConfigOptions”接口的对象。

services.AddSingleton<IConfigOptions>(obj => new ConfigOptions        
{
   Param1 = Configuration["Options:Param1"],
   Param2 = Configuration["Options:Param2"],
   Param3 = Configuration["Options:Param3"],
   <etc>
});

建议?

【问题讨论】:

    标签: c# asp.net-core asp.net-core-webapi


    【解决方案1】:

    在 C# 中的 Configuration 中有一个方法,它会自动从 appsettings 中为您读取所有属性。

    如果对象的属性与 JSON 中的名称匹配,则可以执行以下操作:

    services.AddSingleton<IConfigOptions,ConfigOptions>(_ =>
                  Configuration
                      .GetSection(nameof(ConfigOptions))
                      .Get<ConfigOptions>());
    

    appsettings.json 看起来像:

      "ConfigOptions": {
          "Param1": "text1",
          "Param2": "text2",
          "Param3": "text3"
      }
    

    ConfigOptions 如下所示:

    public class ConfigOptions {
         public string Param1 { get; set; }
         public string Param2 { get; set; }
         public string Param3 { get; set; }
    }
    

    【讨论】:

    • 谢谢。我已经盯着这个太久了,需要另一双眼睛。我知道我忽略了一个相当简单的答案,但我太脑残了,看不到它。 :-)
    【解决方案2】:

    这样吗?

     var config = new MailConfiguration();
       _configuration.Bind("Outbox.Email", config);
       
    
      "Outbox.Email": {
        "smtp": "smtp.com",
        "port": 587,
        "user": "user@user.com",
        "from": "user name",
        "password": "669855,",
      },
    

    【讨论】:

      【解决方案3】:

      例如,在 startup.cs 文件中,您应该有配置属性

         public IConfiguration Configuration { get; }
      

      然后您可以编写以下内容:

      var modelConfiguration = Configuration
                      .GetSection("Section")
                      .Get<YourModel>();
                  services.AddSingleton(modelConfiguration );
      

      "Section" : 表示 app.settings.json 文件中的section

      YourModel :表示在 app.settings 部分中充当参数容器的类

      services.AddSingleton(modelConfiguration ):使用 DI 使其可访问

      【讨论】:

      • 谢谢...这很接近。我标记为“已回答”的响应将其与 DI 所需的界面相关联。
      猜你喜欢
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      相关资源
      最近更新 更多