分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

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

发布时间:2023-09-06 01:49责任编辑:郭大石关键词:配置

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

 

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

原文地址:https://www.cnblogs.com/liyouming/p/8856682.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved