如何在Net Core中使用ConfigurationManager读取全局配置
创始人
2024-11-27 18:02:05
0次

一、引入扩展System.Configuration.ConfigurationManager

这个扩展库可以直接在Nuget中获取。

使用方法和说明见.NET Core 2.0迁移技巧之web.config配置文件

读取的文件类型和方法都跟.Net Framework中一致,而且仅需引入包就可以,瞬间很兴奋有木有!

但是!在使用过过程中发现这个扩展有问题。项目运行过程中需修改我的app.config文件,对我项目中输出的内容没有丝毫影响,Debug发现获取到的值的确没有变化。重启项目都没有用。只有把项目重新编译才好使。

不知道是不是因为我的打开方式不对,但是最终放弃这个方法。

二、引入扩展Microsoft.Extensions.Options.ConfigurationExtensions

这个扩展库也可以直接在Nuget中获取。

使用方法和说明见 ASP.NET Core实现类库项目读取配置文件

这个可以读取application.json中的配置参数,不再使用XML可以说很好的贴近Core的设计理念。

  可惜,这个也有点美中不足的地方。首先跟上面的那个一样,运行时修改json文件读取到的内容不会改变,但是至少重启项目可以修改,这个让我欣慰很多。另外就是,这个方法采用的是反序列化的原理,也就是必须有一个跟配置文件对应的实体类才可以,这个感觉比较鸡肋,放弃。

三、自定义扩展方法

这个是我这次说的重点,要是前面两个方法能满足读者你的需求,那么就没有必要看下去。

废话少说,先上代码:

public class ConfigurationManager
  {
    /// 
    /// 配置内容
    /// 
    private static NameValueCollection _configurationCollection = new NameValueCollection();

    /// 
    /// 配置监听响应链堆栈
    /// 
    private static Stack> FileListeners = new Stack>();

    /// 
    /// 默认路径
    /// 
    private static string _defaultPath = Directory.GetCurrentDirectory() + "\\appsettings.json";

    /// 
    /// 最终配置文件路径
    /// 
    private static string _configPath = null;

    /// 
    /// 配置节点关键字
    /// 
    private static string _configSection = "AppSettings";

    /// 
    /// 配置外连接的后缀
    /// 
    private static string _configUrlPostfix = "Url";

    /// 
    /// 最终修改时间戳
    /// 
    private static long _timeStamp = 0L;

    /// 
    /// 配置外链关键词,例如:AppSettings.Url
    /// 
    private static string _configUrlSection { get { return _configSection + "." + _configUrlPostfix; } }


    static ConfigurationManager()
    {
      ConfigFinder(_defaultPath);
    }

    /// 
    /// 确定配置文件路径
    /// 
    private static void ConfigFinder(string Path)
    {
      _configPath = Path;
      JObject config_json = new JObject();
      while (config_json != null)
      {
        config_json = null;
        FileInfo config_info = new FileInfo(_configPath);
        if (!config_info.Exists) break;

        FileListeners.Push(CreateListener(config_info));
        config_json = LoadJsonFile(_configPath);
        if (config_json[_configUrlSection] != null)
          _configPath = config_json[_configUrlSection].ToString();
        else break;
      }

      if (config_json == null || config_json[_configSection] == null) return;

      LoadConfiguration();
    }

    /// 
    /// 读取配置文件内容
    /// 
    private static void LoadConfiguration()
    {
      FileInfo config = new FileInfo(_configPath);
      var configColltion = new NameValueCollection();
      JObject config_object = LoadJsonFile(_configPath);
      if (config_object == null || !(config_object is JObject)) return;
      
      if (config_object[_configSection]!=null)
      {
        foreach (JProperty prop in config_object[_configSection])
        {
          configColltion[prop.Name] = prop.Value.ToString();
        }
      }
      
      _configurationCollection = configColltion;
    }

    /// 
    /// 解析Json文件
    /// 
    /// 文件路径
    /// 
    private static JObject LoadJsonFile(string FilePath)
    {
      JObject config_object = null;
      try
      {
        StreamReader sr = new StreamReader(FilePath, Encoding.Default);
        config_object = JObject.Parse(sr.ReadToEnd());
        sr.Close();
      }
      catch { }
      return config_object;
    }

    /// 
    /// 添加监听树节点
    /// 
    /// 
    /// 
    private static KeyValuePair CreateListener(FileInfo info)
    {

      FileSystemWatcher watcher = new FileSystemWatcher();
      watcher.BeginInit();
      watcher.Path = info.DirectoryName;
      watcher.Filter = info.Name;
      watcher.IncludeSubdirectories = false;
      watcher.EnableRaisingEvents = true;
      watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size;
      watcher.Changed += new FileSystemEventHandler(ConfigChangeListener);
      watcher.EndInit();

      return new KeyValuePair(info.FullName, watcher);
     
    }

    private static void ConfigChangeListener(object sender, FileSystemEventArgs e)
    {
      long time = TimeStamp();
      lock (FileListeners)
      {
        if (time > _timeStamp)
        {
          _timeStamp = time;
          if (e.FullPath != _configPath || e.FullPath == _defaultPath)
          {
            while (FileListeners.Count > 0)
            {
              var listener = FileListeners.Pop();
              listener.Value.Dispose();
              if (listener.Key == e.FullPath) break;
            }
            ConfigFinder(e.FullPath);
          }
          else
          {
            LoadConfiguration();
          }
        }
      }
    }

    private static long TimeStamp()
    {
      return (long)((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds * 100);
    }

    private static string c_configSection = null;
    public static string ConfigSection
    {
      get { return _configSection; }
      set { c_configSection = value; }
    }


    private static string c_configUrlPostfix = null;
    public static string ConfigUrlPostfix
    {
      get { return _configUrlPostfix; }
      set { c_configUrlPostfix = value; }
    }

    private static string c_defaultPath = null;
    public static string DefaultPath
    {
      get { return _defaultPath; }
      set { c_defaultPath = value; }
    }

    public static NameValueCollection AppSettings
    {
      get { return _configurationCollection; }
    }

    /// 
    /// 手动刷新配置,修改配置后,请手动调用此方法,以便更新配置参数
    /// 
    public static void RefreshConfiguration()
    {
      lock (FileListeners)
      {
        //修改配置
        if (c_configSection != null) { _configSection = c_configSection; c_configSection = null; }
        if (c_configUrlPostfix != null) { _configUrlPostfix = c_configUrlPostfix; c_configUrlPostfix = null; }
        if (c_defaultPath != null) { _defaultPath = c_defaultPath; c_defaultPath = null; }
        //释放掉全部监听响应链
        while (FileListeners.Count > 0)
          FileListeners.Pop().Value.Dispose();
        ConfigFinder(_defaultPath);
      }
    }

}

最开始设计的是采用缓存,每次调用比对文件的修改时间,大小等特征,出现变化从新载入配置。后来发现图样图森破!

C#提供了专门监听文件系统的方法。所以从新设计了监听响应链堆栈来实现。

使用说明:

1、配置节点:

可以直接写在项目默认的配置文件appsettings.json中 格式如下

{
 "AppSettings": {
  "Title": "Test",
  "Version": "1.2.1",
  "AccessToken": "123456@abc.com"
 }
}

保证配置节点AppSettings存在,剩下的就是以Key-Value的形式来写属性,就可以。

2、外部配置文件

像.Net Framework中一样,可以通过外部配置文件来实现。格式如下

{
  "AppSettings.Url": "D:\\test\\app1.json"
}

采用格式是“配置节点名.外链后缀”的形式。可以设计多级外部配置文件,只要发现有外部配置节点就会向下寻找,并监听链上的所有节点文件的变化。

但是需要注意的是:一旦存在外部配置节点,此文件中的配置节点和参数将不再参与解析

3、可配置初始化参数

包括默认文件路径在内的多个参数均可以修改,详情见代码。

修改后需要手动调用RefreshConfiguration方法,以使配置内容生效,有点像事务处理。建议在项目的Startup方法中修改配置方法。

4、使用

跟.Net Framework中一样,直接调用ConfigurationManager.Appsettings["Title"]就可以了。

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...