【问题标题】:Concatenating .NET Core Configuration连接 .NET Core 配置
【发布时间】:2023-03-28 23:36:02
【问题描述】:

有没有一种简单的方法来连接配置以避免冗余?

  "Directories": {
    "Root": "my\\root\\folder",
    "Log": "{Root}\\Log",
    "Data": "{Root}\\Data" 
  }

我可以将 {Root} 作为变量传递,而不是编写每个目录的完整路径。这样,用户只需要更新 1 个配置行而不是全部 3 个。

当我调用Configuration["Directories:Log"] 时,它返回为my\\root\\folder\\Log。数据和其他可能的组合也是如此。基本上如果可能的话,我想在配置文件(appsettings.json)中使用其他配置作为变量。

【问题讨论】:

  • 简短回答:否。然而,这是一个实现问题,您可以在服务中实现自己。

标签: c# asp.net-core


【解决方案1】:

创建一个类来表示您的设置,然后创建可以满足您需求的方法,例如下面。可以在 .NET Core 控制台应用程序中执行此操作,也不必是 ASP.NET Core。

    public class YourSettings
    {
        public string Root { get; set; }
        public string Log { get; set; }
        public string Data { get; set; }

        public string LogPath => Log.Replace("{Root}", Root);
        public string DataPath => Data.Replace("{Root}", Root);
    }

然后注册:

    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
       ...
       // Configure Options using Microsoft.Extensions.Options.ConfigurationExtensions
        services.Configure<YourSettings>(Configuration.GetSection(nameof(YourSettings))); // for your specific example just pass in the string "Directories" since you don't have a section called "YourSettings" - obviously just update the class to encompass whatever settings you want it to
        services.AddSingleton(Configuration); //for DI
       ...
    }

然后使用它:

    private readonly YourSettings _settings;
    public YourController(IOptions<YourSettings> settings)
    {
        _spDataRepo = spDataRepo;
        _settings = settings.Value;
        DoStuffWithSettings();
    }

    public void DoStuffWithSettings()
    {
        Debug.Print($"Hey the logs are here: {_settings.LogPath}");
    }

【讨论】:

  • 或者(对其他人来说更乏味且不那么直接),您可以编写一个 MSBuild 任务来执行此操作,请参阅此处答案下方的解决方案:stackoverflow.com/questions/7837644/…
  • 感谢马克的建议,我实际上正在寻找一种更动态的方法。我只是使用一些基本示例,但“真实”配置更复杂。我想调用 Configuration["config:path"] 而不是强类型 _settings.LogPath
  • @dfox 恐怕我不遵循 - 配置不应该太动态 - 但即便如此,如果类型是问题(这很奇怪),那么只需在 C# 中使用对象而不是特定类型代表您的配置的类。
猜你喜欢
  • 2021-10-29
  • 2020-05-24
  • 2018-03-05
  • 1970-01-01
  • 2021-11-01
  • 2020-08-17
  • 2017-11-15
  • 1970-01-01
  • 2019-01-07
相关资源
最近更新 更多