【问题标题】:How to unprefix configuration section item?如何取消配置部分项的前缀?
【发布时间】:2020-12-07 16:15:12
【问题描述】:

要配置我的服务,我需要按实例设置单例,如下所示:

        IConfigurationSection settingsSection = Configuration.GetSection("AppSettings");
        MySettings settings = new MySettings();
        settingsSection.Bind(settings);

        // something to do with the instance, so I need it here

        services.Configure<MySettings>(settings);

当我检查 settingsSection 项目时,我看到它的键都以 Appsettings: 为前缀(即:AppSettings:AppIdAppSettings:AppUrl、...)。

因此,绑定未完成,我的 settings 对象未初始化。

有没有办法阻止这个前缀,因为我已经知道我在那个部分?

下面是 appsettings.json 的样子:

{
  "AppSettings": {
    "AppId": 3540350,
    "AppUrl": "http://localhost:542",
    "AppEnabled": true,
    ...
  }
}

MySettings 类如下所示:

public class MySettings
{
    public int AppId { get; set;}
    public string AppUrl { get; set;}
    public bool AppEnabled { get; set;}
    ...
}

编辑

我愚蠢地保留了一个无法反序列化的旧命名约定(我猜):

{
  "AppSettings": {
    "App.Id": 3540350,
    "App.Url": "http://localhost:542",
    "App.Enabled": true,
    ...
  }
}

这个问题可以结束了。

【问题讨论】:

  • 有一个扩展方法可以接收该部分并配置IOptions,因此您只需执行services.Configure&lt;MySettings&gt;(Configuration.GetSection("AppSettings"))之类的操作
  • @dcg "我需要按实例设置单例"

标签: c# dependency-injection configuration


【解决方案1】:

如果你想让settings 成为单例,我想你可以使用IConfigurationSection 的扩展方法Get,如下所示:

var settings = configuration.GetSection("AppSettings").Get<MySettings>();
services.AddSingleton(settings);

正在运行的示例 Web 项目的图像:

【讨论】:

  • 已经尝试过,该部分有正确的项目,但实例未初始化。我猜是因为注射还没有完成。
  • 嗯,我敢肯定我以前做过,而且工作正常。
  • 顺便说一句,AppId 是一个整数,但在配置中是一个字符串。
  • @sinsedrix 我刚刚在一个示例 Web 项目中复制了它并且它正在工作。我用注入到HomeController 中的MySettings 实例的详细信息搭建了一个视图,它显示了appsettings.json 文件中的值。
【解决方案2】:

我不认为前缀是问题所在。如果您想要配置的单例实例,您应该能够执行以下操作:

services.Configure<MySettings>(Configuration.GetSection("AppSettings"));
services.AddSingleton(provider => provider.GetRequiredService<IOptionsSnapshot<MySettings>>().Value);

然后您应该能够将MySettings 直接注入到控制器的构造函数参数中。

如果注册后直接需要,也可以这样做:

services.Configure<MySettings>(Configuration.GetSection("AppSettings"));
var provider = services.BuildServiceProvider();
var settings = provider.GetRequiredService<IOptionsSnapshot<MySettings>>().Value;

【讨论】:

  • 我不在控制器上下文中,这就是为什么我需要按实例设置单例
  • 我的答案的第二部分对你有用还是前缀看起来仍然可疑?
  • 我不会将一个部分传递给配置,而是一个实例,所以问题是填充实例
猜你喜欢
  • 2022-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-30
  • 2016-04-20
  • 1970-01-01
  • 2012-02-12
  • 1970-01-01
相关资源
最近更新 更多