使用.Net 6
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Abstractions" Version="6.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="6.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="6.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.1" />
</ItemGroup>
<ItemGroup>
<None Update="config.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
建立一个配置文件, 并设置为更新时复制
{
"name": "zg",
"age": 18,
"proxy": {"address": "aa","port": "8080"}
}
// See https://aka.ms/new-console-template for more information
using Microsoft.Extensions.Configuration;
ConfigurationBuilder cfgBuilder = new ConfigurationBuilder();
//optional: true 可以检测报错 reloadOnChange: true 自动加载. json设置成更新时复制
cfgBuilder.AddJsonFile("config.json", optional: true, reloadOnChange: true);
IConfigurationRoot configRoot = cfgBuilder.Build();
Console.WriteLine("--------------原始方法----------------------------------");
string name = configRoot["name"];
Console.WriteLine($"name={name}");
string add = configRoot.GetSection("proxy:address").Value;
Console.WriteLine($"addr={add}");
Console.WriteLine("--------------使用微软的Configuration.Binder----------------------------------");
//使用微软的Configuration.Binder
Proxy proxy = configRoot.GetSection("proxy").Get<Proxy>();
Console.WriteLine($"IP地址是:{ proxy.Address},端口号是{proxy.Port}");
Console.WriteLine("--------------直接读取根节点----------------------------");
Config config = configRoot.Get<Config>();
Console.WriteLine($"姓名是{config.Name}, 年龄是{config.Age}, IP地址是:{ config.Proxy.Address},端口号是{config.Proxy.Port}");
class Proxy
{
public string Address { get; set; }
public string Port { get; set; }
}
class Config
{
public string Name { get; set; }
public string Age { get; set; }
public Proxy Proxy { get; set; }
}
结果:
--------------原始方法----------------------------------
name=zg
addr=aa
--------------使用微软的Configuration.Binder----------------------------------
IP地址是:aa,端口号是8080
--------------直接读取根节点----------------------------
姓名是zg, 年龄是18, IP地址是:aa,端口号是8080
E:\Csharp\ConfigTestDemon\ConfigTestDemon\bin\Debug\net6.0\ConfigTestDemon.exe (进程 8608)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .
使用依赖注入的方式:
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfigTestDemon
{
public class TestController
{
//private IOptionsSnapshot<Config> optConfig;
private IOptionsSnapshot<Config> optConfig;
public IOptionsSnapshot<Config> OptConfig
{
get { return optConfig; }
set { optConfig = value; }
}
public TestController(IOptionsSnapshot<Config> optConfig) => this.optConfig = optConfig;
public void Test()
{
Console.WriteLine(optConfig.Value.Age);
Console.WriteLine("---------------");
Console.WriteLine(optConfig.Value.Proxy.Address);
}
}
}
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfigTestDemon
{
public class OnlyProxy
{
private IOptionsSnapshot<Proxy> optProxy;
public OnlyProxy(IOptionsSnapshot<Proxy> optProxy)
{
this.optProxy = optProxy;
}
public void Test()
{
Console.WriteLine($"用OnlyProxy实现IP为{optProxy.Value.Address},端口号为:{optProxy.Value.Port}");
}
}
}
//Console.WriteLine("--------------使用DI依赖注入----------------------------");
ConfigurationBuilder cfgBuilder = new ConfigurationBuilder();
//使用CommandLine
//optional: true 可以检测报错 reloadOnChange: true 自动加载. json设置成更新时复制
cfgBuilder.AddJsonFile("config.json", optional: true, reloadOnChange: true);
IConfigurationRoot configRoot = cfgBuilder.Build();
ServiceCollection services = new ServiceCollection(); //构造容器对象
services.AddScoped<TestController>(); //注册
services.AddScoped<OnlyProxy>();
//将Config对象绑在根节点configRoot 读取配置时, 要声明AddOptions
services.AddOptions()
.Configure<Config>(e => configRoot.Bind(e))
.Configure<Proxy>(e => configRoot.GetSection("proxy").Bind(e));
using (ServiceProvider sp = services.BuildServiceProvider()) //创建provider对象
{
while (true)
{
await Task.Delay(1000);
using (var scope = sp.CreateScope())
{
//新建CreateScope 可以自动刷新文本json的改变
Console.WriteLine("-----------读取完整的TestController---Test方法实现----------------------------");
var c = sp.GetRequiredService<TestController>();
c.Test();
Console.WriteLine("-----------只读取Proxy的地址和端口号---Test方法实现----------------------------");
var c2 = sp.GetRequiredService<OnlyProxy>();
c2.Test();
}
}
/*
* 结果:
--------------使用DI依赖注入----------------------------
-----------读取完整的TestController---Test方法实现----------------------------
18
---------------
aa
-----------只读取Proxy的地址和端口号---Test方法实现----------------------------
用OnlyProxy实现IP为aa,端口号为:8080
*/
}
public class Proxy
{
public string? Address { get; set; }
public string? Port { get; set; }
}
public class Config
{
public string? Name { get; set; }
public string? Age { get; set; }
public Proxy? Proxy { get; set; }
}
1191

被折叠的 条评论
为什么被折叠?



