using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using System.Collections.Concurrent; namespace learun.util { /// /// 版 本 EasyCode EC管理后台 /// Copyright (c) 2019-present EC管理有限公司 /// 创建人:tobin /// 日 期:2019.09.02 /// 描 述:对HtmlHelper类进行扩展 /// public static class ConfigHelper { /// /// 缓存数据(配置信息) /// private static readonly ConcurrentDictionary _setting = new ConcurrentDictionary(); /// /// 缓存数据 /// private static readonly ConcurrentDictionary _cache = new ConcurrentDictionary(); private static IConfiguration configuration; /// /// 获取配置信息 /// /// 数据类型 /// 键 /// public static T GetAppSettings(string key) where T : class, new() { if (configuration == null) { string fileName = "appsettings.json"; if (GetValue("env") == "dev") { fileName = "appsettings.Development.json"; } var directory = ConfigHelper.GetValue("baseDir"); var filePath = $"{directory}/{fileName}"; var builder = new ConfigurationBuilder(); builder.AddJsonFile(filePath, false, true); configuration = builder.Build(); } // 获取bin目录路径 //if (!File.Exists(filePath)) //{ // var length = directory.IndexOf("/bin", StringComparison.Ordinal); // filePath = $"{directory.Substring(0, length)}/{fileName}"; //} //IConfiguration configuration; var appconfig = new ServiceCollection() .AddOptions() .Configure(configuration.GetSection(key)) .BuildServiceProvider() .GetService>() .Value; return appconfig; } /// /// 获取配置信息 /// /// public static ServerOp GetConfig() { return GetAppSettings("ServerOp"); } /// /// 设置信息 /// /// 键 /// 值 public static void SetValue(string key, object value) { _setting.GetOrAdd(key, value); } /// /// 获取数据值 /// /// 类型 /// 键值 /// public static T GetValue(string key) where T : class { _setting.TryGetValue(key, out object result); return result as T; } /// /// 设置信息 /// /// 键 /// 值 public static void SetCache(string key, string value) { _cache.GetOrAdd(key, value); } /// /// 获取数据值 /// /// 键值 /// public static string GetCache(string key) { _cache.TryGetValue(key, out string result); return result; } } }