.Net Core配置系统

目录

Json文件配置

读取配置原始方法

绑定读取配置

用法


  1. 传统Web.config配置的缺点
  2. 为了兼容,仍然可以使用Web.config和ConifgurationManager类,但不推荐
  3. .NET中的配置系统支持丰富的配置源,包括文件(json、xml、ini等)、注册表、环境变量、命令行、Azure Key Vault等,还可以配置自定义配资源。可以跟踪配置的改变,可以按照优先级覆盖。

Json文件配置

  1. 创建一个json文件,文件名随意,比如config.json,设置"如果较新则复制"
  2. NuGet安装Microsoft.Extensions.Configuration和Microsoft.Extensions.Configuration.Json
  3. 编写代码,先用简单的方式读取配置

{

"name": "ljy",

"age": "18",

"proxy": {

"address": "aa",

"port": "80"

}

}

读取配置原始方法
cs 复制代码
//创建配置构建器实例
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
//添加JSON配置文件
configurationBuilder.AddJsonFile("config.json", optional: true, reloadOnChange: true);
//构建配置根对象
IConfigurationRoot config = configurationBuilder.Build();
//读取"name"配置项
string name = config["name"];
//读取"proxy:address"配置项
string proxyAddress = config.GetSection("proxy:address").Value;
  • optional:表示文件是否可选,建议optional设置为false,这样写错可及时发现
  • reloadOnChange:表示如果文件修改了,是否重新加载配置
绑定读取配置
  1. 可以绑定一个类,自动完成配置的读取
  2. NuGet安装:Microsoft.Extensions.Configuration.Binder
  3. Server server=configRoot.GetSection("proxy").Get<Server>()
cs 复制代码
class Program
{
    static void Main(string[] args)
    {
        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.AddJsonFile("config.json", optional: true, reloadOnChange: true);
        IConfigurationRoot configRoot = configurationBuilder.Build();
        //1
        //string name = configRoot["name"];
        //Console.WriteLine($"name={name}");
        //string address = configRoot.GetSection("proxy:address").Value;
        //Console.WriteLine($"address={address}");

        //2
        //Proxy proxy = configRoot.GetSection("proxy").Get<Proxy>();
        //Console.WriteLine($"{proxy.Address},{proxy.Port}");

        //3
        Config config =configRoot.Get<Config>();
        Console.WriteLine(config.Name);
        Console.WriteLine(config.Proxy.Address);
    }
}
class Config
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Proxy Proxy { get; set; }
}
class Proxy
{
    public string Address { get; set; }
    public int Port { get; set; }
}
用法
  1. 推荐使用选项方式读取,和DI结合更好,且更好利用"reloadonchange"机制
  2. Nuget安装:Microsoft.Extensions.Options、Microsoft.Extensions.Configuration.Binder、Microsoft.Extensions.Configuration、Microsoft.Extensions.Configuration.Json
  3. 读取配置的时候,DI要声明IOptions<T>、IOptionsMonitor<T>、IOptionsSnapshot<T>等类型。IOptions<T>不会读取到新的值;和IOptionsMonitor相比,IOptionsSnapshot会在同一个范围内(比如ASP.NET Core一个请求中)保持一致。建议用IOptionsSnapshot
cs 复制代码
class Program
{
    static void Main(string[] args)
    {
        ServiceCollection services = new ServiceCollection();
        services.AddScoped<TestController>();
        services.AddScoped<Test2>();

        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.AddJsonFile("config.json", optional: true, reloadOnChange: true);
        IConfigurationRoot configRoot = configurationBuilder.Build();
        //使用services.AddOptions()方法将选项框架注册到服务容器中,Configure<Config>方法来配置Config类的实例。configRoot.Bind(e)是将配置根绑定到Config类的实例上,这样就可以从配置文件中读取相应的配置值并填充到Config类的属性中
        services.AddOptions()
            .Configure<Config>(e => configRoot.Bind(e))
            .Configure<Proxy>(e => configRoot.GetSection("proxy").Bind(e));

        using (var sp = services.BuildServiceProvider())
        {
            var c = sp.GetRequiredService<TestController>();
            c.Test();
            var c2 = sp.GetRequiredService<Test2>();
            c2.Test();
        }
    }
}

class Config
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Proxy Proxy { get; set; }
}

class Proxy
{
    public string Address { get; set; }
    public int Port { get; set; }
}

class TestController
{
    private readonly IOptionsSnapshot<Config> optConfig;
    public TestController(IOptionsSnapshot<Config> optConfig)
    {
        this.optConfig = optConfig;
    }

    public void Test()
    {
        Console.WriteLine(optConfig.Value.Age);
        Console.WriteLine(optConfig.Value.Proxy.Port);
    }
}

class Test2
{
    private readonly IOptionsSnapshot<Proxy> optProxy;
    public Test2(IOptionsSnapshot<Proxy> optProxy)
    {
        this.optProxy = optProxy;
    }

    public void Test()
    {
        Console.WriteLine(optProxy.Value.Address);
    }
}
相关推荐
我材不敲代码29 分钟前
Python实现打包贪吃蛇游戏
开发语言·python·游戏
身如柳絮随风扬1 小时前
Java中的CAS机制详解
java·开发语言
韩立学长3 小时前
【开题答辩实录分享】以《基于Python的大学超市仓储信息管理系统的设计与实现》为例进行选题答辩实录分享
开发语言·python
froginwe113 小时前
Scala 循环
开发语言
m0_706653233 小时前
C++编译期数组操作
开发语言·c++·算法
故事和你914 小时前
sdut-Java面向对象-06 继承和多态、抽象类和接口(函数题:10-18题)
java·开发语言·算法·面向对象·基础语法·继承和多态·抽象类和接口
Bruk.Liu4 小时前
(LangChain实战2):LangChain消息(message)的使用
开发语言·langchain
qq_423233904 小时前
C++与Python混合编程实战
开发语言·c++·算法
m0_715575344 小时前
分布式任务调度系统
开发语言·c++·算法
csbysj20204 小时前
选择(Selectable)
开发语言