串联.NET Core配置

时间:2019-06-25 02:15:07

标签: c# asp.net-core

是否有一种简便的方法来连接配置以避免冗余?

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

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

当我致电Configuration["Directories:Log"]时,它将返回为my\\root\\folder\\Log。与Data和其他可能的组合相同。基本上,如果可能的话,我想将其他配置用作配置文件(appsettings.json)中的变量。

1 个答案:

答案 0 :(得分:4)

创建一个类来表示您的设置,然后创建将执行您想要的操作的方法,例如下面。也可以在.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}");
    }