using Microsoft.Extensions.Configuration; using System; using System.IO; namespace Admin.Core.Common.Helpers { /// /// 配置帮助类 /// public class ConfigHelper { /* 使用热更新 var uploadConfig = new ConfigHelper().Load("uploadconfig", _env.EnvironmentName, true); services.Configure(uploadConfig); private readonly UploadConfig _uploadConfig; public ImgController(IOptionsMonitor uploadConfig) { _uploadConfig = uploadConfig.CurrentValue; } */ /// /// 加载配置文件 /// /// 文件名称 /// 环境名称 /// 自动更新 /// public IConfiguration Load(string fileName, string environmentName = "", bool reloadOnChange = false) { var filePath = Path.Combine(AppContext.BaseDirectory, "configs"); if (!Directory.Exists(filePath)) return null; var builder = new ConfigurationBuilder() .SetBasePath(filePath) .AddJsonFile(fileName.ToLower() + ".json", true, reloadOnChange); if (environmentName.NotNull()) { builder.AddJsonFile(fileName.ToLower() + "." + environmentName + ".json", optional: true, reloadOnChange: reloadOnChange); } return builder.Build(); } /// /// 获得配置信息 /// /// 配置信息 /// 文件名称 /// 环境名称 /// 自动更新 /// public T Get(string fileName, string environmentName = "", bool reloadOnChange = false) { var configuration = Load(fileName, environmentName, reloadOnChange); if (configuration == null) return default; return configuration.Get(); } /// /// 绑定实例配置信息 /// /// 文件名称 /// 实例配置 /// 环境名称 /// 自动更新 public void Bind(string fileName, object instance, string environmentName = "", bool reloadOnChange = false) { var configuration = Load(fileName, environmentName, reloadOnChange); if (configuration == null || instance == null) return; configuration.Bind(instance); } } }