Fork me on GitHub

.NetCore读取配置Json文件到类中并在程序使用

ConfigurationBuilder 这个类提供了配置绑定,在dnc中 Program中WebHost提供了默认的绑定(appsettings文件)

如果我们需要加载我们自己的json配置文件怎么处理

 var builder = new ConfigurationBuilder();

这里builder 提供了很多添加的方式

1、第一种:直接添加json文件路径,这里需要注意的json文件地址问题

  builder.AddJsonFile("path").Build();

2、第二种

  builder.Add("IConfigurationSource的实例")
builder.Add(new JsonConfigurationSource { Path = "WebSiteConfig.json", Optional = false, ReloadOnChange = true }).Bind();

配置好了 建立对应的json文件对应的实体模型类

在服务里面配置一下:

services.Configure<WebSiteConfig>(Configuration);//配置

比如数据库连接字符串的配置处理,或者系统中的固定配置,这里我扩展了下 NPoco的服务扩展添加

services.AddNPocoContext(options =>
            {
                options.connectionstring = Configuration.Get<WebSiteConfig>().ConnectionStr;

            });

在系统中业务层或者其他层次怎么来获取这个配置

这里需要用的一个接口IOptions

在服务中添加注入下相关类

services.AddOptions();

 

比如在我们的测试类中注入相关IOptions的模型类

private IOptions<NPocoDataBaseSetting> _options;
        private IOptions<WebSiteConfig> _website;
        private ITestRepository _testservices;
        private ITransaction _transaction;
        public TestServices(IServiceProvider serviceProvider, IOptions<NPocoDataBaseSetting> options, ITransaction transaction, IOptions<WebSiteConfig> website, ITestRepository testservices)
        {
            _options = options;
            _testservices = testservices;
            _transaction = transaction;
            _website = website;
        }

如:

IOptions<WebSiteConfig> _website ,我们可以通过
  /// <summary>
        /// 测试获取数据
        /// </summary>
        /// <returns></returns>
        public List<Test> getdata()
        {
            string webname = _website.Value.WebName;
            List<Test> list = new List<Test>();
            try
            {
                _transaction.Begin();
               
                list = _testservices.test();
                _transaction.Commit();

            }
            catch (Exception)
            {
                _transaction.RollBack();

            }
            return list;

        }

获取到webname,这里值得注意的json文件中文乱码问题,要确定好json文件的编码类型 UTF-8

 

 

posted @ 2018-04-16 16:37  龙码精神  阅读(2496)  评论(0编辑  收藏  举报