.net core 2.0學習筆記(五):程序配置&ConfigurationManager


     配置組件是.net framework中非常常用的功能。在創建.net framework 工程時,系統不僅會自動生成app.config文件,而且還提供了非常強大的訪問類庫。但是這些好東西,在.net core 2.0中已經不復存在,至少說沒有.net framework 中那么完美了。

     在升級.net framework 程序到.net core 2.0時,如果通過.NET Portability Analyzer分析代碼,會發現下面的提示,.net core:supported 2.0+,.net standard:not supported.雖然.net 2.0暫時不支持,但是微軟提供的擴展類庫是支持的,需要自己找Microsoft.Extention類庫去。

Image(52)

     好吧。既然Core 2.0中沒有COnfigurationManager,我們就簡單封裝一個吧。首先,創建一個.net core 2.0 的類庫工程.

Image(53)

然后打開nuget包管理。輸入:Microsoft.Extensions.Configuration.Json,然后安裝即可。

Image(54)

Image(55)

     在剛才新建的工程中新增類:ConfigurationManager,命名空間可以自定義了。然后,加入下面代碼。

public class ConfigurationManager
    {
        private static IConfigurationRoot config = null;
        static ConfigurationManager()
        {
            // Microsoft.Extensions.Configuration擴展包提供的
            var builder = new ConfigurationBuilder()
                .AddJsonFile("app.json");
            config = builder.Build();
        }

       public static IConfigurationRoot AppSettings
        {
            get
            {
                return config;
            }
        }

       public static string Get(string key)
        {
            return config[key];
        }

   }

     新建一個.net core 管理控制台程序,並新增加文件:app.config。文件內容為:

{

       "Name": "my-other-value"

}

     在管理控制台程序的Main函數中,編寫下面代碼,同時添加對類庫工程的引用。配置問題比較順利的搞定!  

  static void Main(string[] args)

  {

      Console.WriteLine(ConfigurationManager.AppSettings["Name"]);

      Console.ReadLine();

  }

  

  OK,通過上面努力,終於解決了配置的問題了。但是,有更簡單的方法。直接在nuget管理中搜索:System.Configuration.ConfigurationManager,添加引用后,問題解決。郁悶,微軟提供了這些類庫,不知道為什么不放到公共的類庫中呢?害的我大費周折。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM