.net core 的配置选项

ConfigurationProvider

  提供配置源

ConfigurationBuilder

  用于构建IConfiguration,将不同的配置类型转换为统一的IConfiguration类型。

  内部采用类似键值对的形式,保存所有的叶子节点,这也就是为什么我们可以直接采用 configuration["Root2:Config"] 获得相应的值。

如json配置文件

{
  "Root": {
    "R1": "A",
    "R2": "B",
    "R3": "C"
  },
  "Root2": {
    "Config": [ 1, 2, 3, 4, 5 ]
  },
  "Root3": "2020061"
}

 

ConfigurationRoot

  对象提供为一个配置的根。当ConfigurationProvider重载配置文件时,由于Api调用转移到了IConfigurationProvider,因此获取的值也会变为最新的值。

,ConfigurationSection

  配置节点,此节点被创建出来后,也将代变此节点的根,在此使用的key都指向以此为起的的路径。

 

配置文件是以后来者居上的形式读取的。也就是前面的数据会被后面的数据覆盖。

 

Options模式

通过这种模式,可以利用IOptions<TOptions>来提供我们需要的Options对象。

Configure方法来自nuget包 Microsoft.Extensions.Options;

Configure不一定需要使用IConfiguration,我们也可直接实例化。

var configuration = new ConfigurationBuilder()
                .Build();

            var serviceCollection = new ServiceCollection();
            serviceCollection.AddOptions()
                .Configure<Appsettings>(configuration);

            var serviceProvider = serviceCollection.BuildServiceProvider();
            var appsettings = serviceProvider.GetRequiredService<IOptions<Appsettings>>();

如上面的代码片段,Configure方法会将我们通过的configuration和类Appsettings进行映射。

最后通过获取服务IOptions<Appsettings>的Value属性获取appsettings的实例。

多个绑定

        static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                .AddJsonFile("contactInfo.json", false, true)
                .Build();

            var serviceCollection = new ServiceCollection();
            serviceCollection.AddOptions()
                .Configure<Contact>("c01", configuration.GetSection("ContactInfo1"))
                .Configure<Contact>("c02", configuration.GetSection("ContactInfo2"));



            var serviceProvider = serviceCollection.BuildServiceProvider();
            var contactSnapshot = serviceProvider.GetRequiredService<IOptionsSnapshot<Contact>>();
            var c1 = contactSnapshot.Get("c01");
            var c2 = contactSnapshot.Get("c02");
        }
{
  "ContactInfo1": {
    "Id": 1,
    "Address": "GZ"
  },
  "ContactInfo2": {
    "Id": 2,
    "Address": "FS"
  }
}

有时候我们可能会许多同一个类型获取不同的配置项,我们可以通过上面的方式,注册多个相同类型的注册项目。

通过IOptionsSnapshot<IOptions>,然后使用配置名可以获得对应的配置项。

 

可以通过IOptionsMonitor<IOptions>监视配置文件改变。

            var optionsContact = serviceProvider.GetRequiredService<IOptionsMonitor<Contact>>();
            optionsContact.OnChange((contact, configName) =>
            {
                Console.WriteLine($"{configName} {contact.Address}");
            });

可以对

serviceCollection.AddOptions<Contact>().Validate(contact =>
{
  return contact.Id < 10;
});

 

配置项进行验证

 

posted @ 2020-06-14 17:27  指左转右  阅读(258)  评论(0编辑  收藏  举报