需要引用包:
Microsoft.Extensions.Configuration
配置文件类库
Microsoft.Extensions.Configuration.Binder
将配置文件转换成实体类的类库
Microsoft.Extensions.Configuration.Json
读取Json文件的类库
Microsoft.Extensions.DependencyInjection
DI类库
Microsoft.Extensions.Options
热加载类库
1. 先创建一个配置文件config.json,并将属性->复制到输出目录->如果较新则复制
config.json内容如下:
{
"name": "张三",
"age": "18",
"students": {
"name": "张同学",
"age": 22
}
}
2. 创建配置文件对象的实体类:
internal class Student
{
public int age { get; set; }
public string Name { get; set; }
}
internal class Teacher
{
public string Name { get; set; }
public int Age { get; set; }
public Student Students { get; set; }
}
3. 创建使用到配置文件的类
internal class Test
{
private readonly IOptionsSnapshot<Teacher> _optionsSnapshot;
//private readonly IOptionsMonitor<Teacher> _optionsMonitor;
public Test(IOptionsSnapshot<Teacher> optionsSnapshot)
//public Test(IOptionsMonitor<Teacher> optionsMonitor)
{
this._optionsSnapshot = optionsSnapshot;
}
public void Run()
{
//Teacher teacher = this._optionsMonitor.CurrentValue;
Teacher teacher = this._optionsSnapshot.Value;
Console.WriteLine(teacher.Name);
Console.WriteLine(teacher.Age);
}
}
IOptionsSnapshot
:在一个范围内,不会重新加载配置文件的内容,但出了范围后如果配置文件内容修改了,则重新加载。
IOptionsMonitor
:配置文件的内容只会在启动时候加载
4. 在Main函数中注册读取配置文件的服务
static void Main(string[] args)
{
// 实例化DI
ServiceCollection services = new ServiceCollection();
// 配置文件构造类
ConfigurationBuilder builder = new ConfigurationBuilder();
// 在类中添加本地的配置文件
builder.AddJsonFile("config.json", false, true);
// 初始化配置文件
IConfigurationRoot config = builder.Build();
// 在DI中注册配置文件的服务
services.AddOptions().Configure<Teacher>(e=>config.Bind(e));
services.AddScoped<Test>();
using(ServiceProvider sp = services.BuildServiceProvider())
{
while (true)
{
// 创建一个范围
using(IServiceScope scope = sp.CreateScope())
{
Test test = scope.ServiceProvider.GetRequiredService<Test>();
test.Run();
Console.ReadKey();
test.Run();
Console.ReadKey();
}
}
}
Console.ReadKey();
}
标签:类库,Console,配置文件,DI,get,Extensions,net,public
From: https://www.cnblogs.com/sunhouzi/p/17866631.html