程序配置&ConfigurationManager

来源:互联网 发布:2017网络机顶盒排行榜 编辑:程序博客网 时间:2024/06/05 14:10

     配置组件是.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跨平台或扫描二维码关注

原创粉丝点击