C#配置系统
读取JSON文件
NuGet两个包:Microsoft.Extensions.Configuration
,Mircosoft.Extensions.Configuration.Json
。
{
"name": "yjw",
"age": 18,
"proxy": {"address": "aa"}
}
需要注意的是,上述json文件,需要设置为”如果较新则复制“,确保在exe同目录下复制该配置文件。
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("config.json", true, true);
IConfigurationRoot configRoot=configurationBuilder.Build();
string name = configRoot["name"];
var age = configRoot["age"];
Console.WriteLine(name);
string address = configRoot.GetSection("proxy:address").Value;
Console.WriteLine(address);
output:
yjw
aa
除了以上的操作,还可以帮定一个类,自动完成配置的读取,NuGet安装:Microsoft.Extensions.Configuration.Binder
。
{
"name": "yjw",
"age": 18,
"proxy": {"address": "aa","port": "80"}
}
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Text;
namespace DITest
{
internal class Program1
{
static void Main()
{
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("config.json", true, true);
IConfigurationRoot configRoot=configurationBuilder.Build();
//GetSection返回IConfigurationSection类型,再使用其Get泛型方法,直接可以得到Proxy类
Proxy proxy =configRoot.GetSection("proxy").Get<Proxy>();
Console.WriteLine($"{proxy.address},{proxy.port}");
Console.ReadKey();
}
}
/// <summary>
/// 具备与json中的proxy里面的key相同的属性名称【首字母大小写都可以】
/// </summary>
class Proxy
{
public string address { get; set; }
public int port { get; set; }
}
}
output:
aa,80
当然也可以直接用一个类来bind根节点
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Text;
namespace DITest
{
internal class Program1
{
static void Main()
{
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("config.json", true, true);
IConfigurationRoot configRoot=configurationBuilder.Build();
Config config = configRoot.Get<Config>();
Console.WriteLine($"{config.Proxy.address},{config.Proxy.port},{config.Name},{config.Age}");
Console.ReadKey();
}
}
class Config
{
public string Name { get; set; }
public string Age { get; set; }
public Proxy Proxy { get; set; }
}
/// <summary>
/// 具备与json中的proxy里面的key相同的属性名称【首字母大小写都可以】
/// </summary>
class Proxy
{
public string address { get; set; }
public int port { get; set; }
}
}
output:
aa,80,yjw,18
选取方式读取
推荐使用选项方式读取,和DI结合更好,且更好利用”reloadOnChange“机制。
NuGet安装:Microsoft.Extensions.Options
,Microsoft.Extensions.Configuration.Binder
。
读取配置的时候,DI要声明IOptions<T>
,IOptionsMonitor<T>
,IOptionsSnapshot<T>
等类型。IOptions<T>
不会读取到新的值;和IOptionsMonitor
相比,IOptionSnapshot<T>
会在同一个范围内保持一致,因此,建议使用IOptionSnapshot
。
Testontrollers.cs
:
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Text;
namespace DITest
{
internal class TestControllers
{
private readonly IOptionsSnapshot<Config> optConfig;//通过IOptinosSnapshot,将配置类注入
public TestControllers(IOptionsSnapshot<Config> optConfig)//通过IOptinosSnapshot,将配置类注入
{
this.optConfig = optConfig;
}
public void Test()
{
Console.WriteLine(optConfig.Value.Name);//通过optConfig.Value获取Config实例
Console.WriteLine(optConfig.Value.Age);
}
}
}
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
namespace DITest
{
internal class Program1
{
static void Main()
{
ServiceCollection sc = new ServiceCollection();
sc.AddScoped<TestControllers>();//注册TestControllers
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("config.json", true, true);
IConfigurationRoot configRoot=configurationBuilder.Build();
sc.AddOptions().Configure<Config>(e=>configRoot.Bind(e));//注册包裹在IOptionSnapshot中的Config
using(var sp = sc.BuildServiceProvider())
{
var c = sp.GetRequiredService<TestControllers>();
c.Test();
}
Console.ReadKey();
}
}
class Config
{
public string Name { get; set; }
public string Age { get; set; }
public Proxy Proxy { get; set; }
}
/// <summary>
/// 具备与json中的proxy里面的key相同的属性名称【首字母大小写都可以】
/// </summary>
class Proxy
{
public string address { get; set; }
public int port { get; set; }
}
}
output:
yjw
18
如果只绑定proxy
:
/// <summary>
/// 只读proxy
/// </summary>
class TestControllers2
{
private readonly IOptionsSnapshot<Proxy> optProxy;
public TestControllers2(IOptionsSnapshot<Proxy> optProxy)
{
this.optProxy = optProxy;
}
public void Test()
{
Console.WriteLine(optProxy.Value.address);
Console.WriteLine(optProxy.Value.port);
}
}
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
namespace DITest
{
internal class Program1
{
static void Main()
{
ServiceCollection sc = new ServiceCollection();
sc.AddScoped<TestControllers>();//注册TestControllers
sc.AddScoped<TestControllers2>();//注册TestControllers2
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("config.json", true, true);
IConfigurationRoot configRoot=configurationBuilder.Build();
sc.AddOptions().Configure<Config>(e=>configRoot.Bind(e)).
Configure<Proxy>(e=>configRoot.GetSection("proxy").Bind(e));//绑定proxy
using(var sp = sc.BuildServiceProvider())
{
var c = sp.GetRequiredService<TestControllers2>();
c.Test();
}
Console.ReadKey();
}
}
class Config
{
public string Name { get; set; }
public string Age { get; set; }
public Proxy Proxy { get; set; }
}
/// <summary>
/// 具备与json中的proxy里面的key相同的属性名称【首字母大小写都可以】
/// </summary>
class Proxy
{
public string address { get; set; }
public int port { get; set; }
}
}
output:
aa
80
命令行方式配置
需要NuGet安装Microsoft.Extensions.Configuration.CommandLine
configBuilder.AddCommandLine(args)
参数支持多种格式,比如server=127.0.0.1
,--server=127.0.0.1
,--server 127.0.0.1
,/server=127.0.0.1
,/server 127.0.0.1
在cmd模式下:xxx.exe name=johnyang age=18
就可以得到该参数.
在VS中,可以在调试属性中,直接写入args
扁平化配置
对于环境变量,命令行等简单的键值对结构,如果想要进行复杂结构的配置,需要进行“扁平化处理”,对于配置的名字需要采用“层级配置”。
比如,json中的
{
"a":{"b":"c"},
"d":{e:[3,5,7]}
}
在cmd中配置为:
a:b:=c d:e:0=3 d:e:1=5 d:e:2=7
C#配置系统的更多相关文章
- .NET Core采用的全新配置系统[10]: 配置的同步机制是如何实现的?
配置的同步涉及到两个方面:第一,对原始的配置文件实施监控并在其发生变化之后从新加载配置:第二,配置重新加载之后及时通知应用程序进而使后者能够使用最新的配置.要了解配置同步机制的实现原理,先得从认识一个 ...
- .NET Core采用的全新配置系统[9]: 为什么针对XML的支持不够好?如何改进?
物理文件是我们最常用到的原始配置的载体,最佳的配置文件格式主要由三种,它们分别是JSON.XML和INI,对应的配置源类型分别是JsonConfigurationSource.XmlConfigura ...
- .NET Core采用的全新配置系统[1]: 读取配置数据
提到“配置”二字,我想绝大部分.NET开发人员脑海中会立马浮现出两个特殊文件的身影,那就是我们再熟悉不过的app.config和web.config,多年以来我们已经习惯了将结构化的配置定义在这两个文 ...
- .NET Core采用的全新配置系统[2]: 配置模型设计详解
在<.NET Core采用的全新配置系统[1]: 读取配置数据>中,我们通过实例的方式演示了几种典型的配置读取方式,其主要目的在于使读者朋友们从编程的角度对.NET Core的这个全新的配 ...
- .NET Core采用的全新配置系统[3]: “Options模式”下的配置是如何绑定为Options对象
配置的原子结构就是单纯的键值对,并且键和值都是字符串,但是在真正的项目开发中我们一般不会单纯地以键值对的形式来使用配置.值得推荐的做法就是采用<.NET Core采用的全新配置系统[1]: 读取 ...
- .NET Core采用的全新配置系统[5]: 聊聊默认支持的各种配置源[内存变量,环境变量和命令行参数]
较之传统通过App.config和Web.config这两个XML文件承载的配置系统,.NET Core采用的这个全新的配置模型的最大一个优势就是针对多种不同配置源的支持.我们可以将内存变量.命令行参 ...
- C# 读取app.config配置文件 节点键值,提示 "配置系统未能初始化" 错误的解决方案
新建C#项目,在app.config中添加了appSettings项,运行时出现"配置系统未能初始化"的错误,MSDN里写到,如果配置文件中包含 configSections 元素 ...
- App.config“配置系统未能初始化” 异常解决 C#
System.Configuration.ConfigurationManager.AppSettings["user"]; 时出现“配置系统未能初始化” 错误 解决办法: 如果配 ...
- CSipSimple配置系统
称作配置系统未免太大了一点,不过它的配置管理这一块确实有加以设计,一方面以增加灵活性,另一方面以支持第三方扩展.通过分析源码,粗略画出如下的结构图: 一.类分析 SharedPreference 一切 ...
- C# “配置系统未能初始化” 异常解决
使用App.config配置参数,读取参数出现错误 “System.Configuration.ConfigurationErrorsException”类型的未经处理的异常在 System.Conf ...
随机推荐
- Normalizing flow 流模型 | CS236深度生成模型Lec8学习笔记
主要参考资料:Stanford University CS236: Deep Generative Models Lec8. 这篇blog基本上是CS236 Lec8的刷课总结/刷课笔记. VAE 这 ...
- 国产化浪潮下,Gitee DevOps 赋能企业数字化创新
在数字化浪潮汹涌的当下,企业竞争白热化,国产数字化创新成为企业突破发展瓶颈.提升核心竞争力的关键 "钥匙".Gitee DevOps 作为国产研发管理领域的佼佼者,凭借强大功能与优 ...
- 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异 引言 在开发 Web 应用时,处理 HTTP 错误响应是常见的任务,尤其是在客户端代码中捕获并向用户展示错误信息.然而,当使用 HTTP ...
- .NET 环境下的三维渲染库 HelixToolkit.SharpDX
1. 引言 在 .NET 生态系统中,三维渲染一直是开发者面临的一个挑战.虽然 WPF 提供了基础的 3D 渲染支持,但性能和功能都较为有限.而 HelixToolkit.SharpDX 作为一款基于 ...
- ShardingSphere分组聚合,数据异常问题
在使用ShardingSphere分组聚合时是,出现了数据汇总不正确问题.我这里只进行了分表,未进行分库.使用的是广播查询,因为是定时任务统计,无法使用到分片键.进行分组的字段是两个 1. SQL查询 ...
- BundleFusion+WIN11+VS2019 + CUDA11.7环境配置
BundleFusion+WIN11+VS2019环境配置 Step1 一开始会提示你重定解决方案,点是即可,如果点错了,也可以在这里再点一次: 简要记录一下环境的配置过程,刚下载下来BundleFu ...
- SpringSecurity5(11-跨域配置)
SpringBoot跨域处理 @CrossOrigin(局部跨域) 作用在方法上 @RestController public class IndexController { @CrossOrigin ...
- JSON Objects Framework(1)
学习datasnap,json必须掌握.用自身的JSON,就必须熟悉JSON Objects Framework.其中tostring和value区别就是一个坑. The JSON objects f ...
- 团队项目:杰杰Bond团队成员介绍
项目 内容 这个作业属于哪个课程 2025年春季软件工程(罗杰.任健) 这个作业的要求在哪里 [T.1] 团队项目:团队成员介绍 我在这个课程的目标是 学习软件工程相关知识,培养编程和团队协作能力,做 ...
- 2024.9.23 cj 训练总结
T1 这道题目仔细观察就会发现: 异或 k=1 这就很好办,考虑 k=1 怎么解 3 1 2 4 5 6 7.......... 即可. 异或,找规律发现有很多数字的异或值为0的.最后的答案是有规律的 ...