程序配置amp;amp;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類庫去。
???? 好吧。既然Core 2.0中沒有COnfigurationManager,我們就簡單封裝一個吧。首先,創建一個.net core 2.0 的類庫工程.
然后打開nuget包管理。輸入:Microsoft.Extensions.Configuration.Json,然后安裝即可。
???? 在剛才新建的工程中新增類: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,添加引用后,問題解決,System.Configuration.ConfigurationManager已經支持.netstandard 2.0。郁悶,微軟提供了這些類庫,不知道為什么不放到公共的類庫中呢?害的我大費周折。
上述代碼等價于使用System.Configuration.ConfigurationManager:
? ? class Program
? ? {
? ? ? ? static void Main(string[] args)
? ? ? ? {
? ? ? ? ? ? var builder = new ConfigurationBuilder()
? ? ? ? ? ? ? ? ? ?.AddJsonFile("app.json");
? ? ? ? ? ? var conStr = ConfigurationManager.AppSettings["Name"];
? ? ? ? ? ? Console.WriteLine($"Hello World! {conStr}");
? ? ? ? }
? ? }
}
點評:
很多包都用Nuget來管理后,有很多人對這個不了解,在此向大家推薦一個微軟的Nuget 包查找網站:?https://packagesearch.azurewebsites.net/
相關文章:?
.NET應用遷移到.NET Core(一)
.NET應用遷移到.NET Core(二)風險評估
.NET應用遷移到.NET Core(三)從商業角度看移植過程
.NET應用遷移到.NET Core--調查案例
遷移傳統.net 應用到.net core [視頻]
應用工具 .NET Portability Analyzer 分析遷移dotnet core
.net core 2.0學習筆記(一):開發運行環境搭建
.net core 2.0學習筆記(二):Hello World & 進階
度量.net framework 遷移到.net core的工作量
遷移.net framework 工程到.net core
原文地址:http://www.cnblogs.com/vveiliang/p/7416370.html
.NET社區新聞,深度好文,微信中搜索dotNET跨平臺或掃描二維碼關注
總結
以上是生活随笔為你收集整理的程序配置amp;amp;ConfigurationManager的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: Orleans简单配置
 - 下一篇: .NET Core 2.0迁移技巧之we