.Net Core Configuration源码探究 (3)

这里我们可以看到既然有Key可以获取字典里对应的Value了,为何还需要Path?通过ConfigurationRoot里的代码我们可以知道Path的初始值其实就是获取ConfigurationSection的Key,说白了其实就是如何获取到当前IConfigurationSection的路径。比如

//当前productSection的Path是 Products:0 IConfigurationSection productSection = configuration.GetSection("Products:0"); //当前productDetailSection的Path是 Products:0:Detail IConfigurationSection productDetailSection = productSection.GetSection("Detail"); //获取到pColor的全路径就是 Products:0:Detail:Color string pColor = productDetailSection["Color"];

而获取Section所有子节点
GetChildrenImplementation来自于IConfigurationRoot的扩展方法

internal static class InternalConfigurationRootExtensions { //// <summary> /// 其实就是在数据源字典里获取Key包含给定Path的所有值 /// </summary> internal static IEnumerable<IConfigurationSection> GetChildrenImplementation(this IConfigurationRoot root, string path) { return root.Providers .Aggregate(Enumerable.Empty<string>(), (seed, source) => source.GetChildKeys(seed, path)) .Distinct(StringComparer.OrdinalIgnoreCase) .Select(key => root.GetSection(path == null ? key : ConfigurationPath.Combine(path, key))); } }

相信讲到这里,大家对ConfigurationSection或者是对Configuration整体的思路有一定的了解,细节上的设计确实不少。但是整体实现思路还是比较清晰的。关于Configuration还有一个比较重要的扩展方法就是将配置绑定到具体POCO的扩展方法,该方法承载在ConfigurationBinder扩展类了,由于实现比较复杂,也不是本篇文章的重点,有兴趣的同学可以自行查阅,这里就不做探究了。

总结

    通过以上部分的讲解,其实我们可以大概的将Configuration配置相关总结为两大核心抽象接口IConfigurationBuilder,IConfiguration,整体结构关系可大致表示成如下关系

.Net Core Configuration源码探究

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wspzdz.html