netcore3.0 IConfiguration配置源码解析(四)
前面三篇介绍了netcore的配置系统,现在我们自己做个扩展
先定义source和provider
public class MyConfigurationSource : IConfigurationSource { public IDictionary<string, string> Data { get; set; } public IConfigurationProvider Build(IConfigurationBuilder builder) { return new MyConfigurationProvider(this); } }
public class MyConfigurationProvider : ConfigurationProvider { public MyConfigurationProvider(MyConfigurationSource soure) { if (soure == null) throw new ArgumentException(nameof(soure)); if (soure.Data == null) throw new ArgumentException(nameof(soure.Data)); foreach (var item in soure.Data) { Data.Add(item.Key, item.Value); } } }
再扩展IConfigurationBuilder
public static class MyConfigurationExtension { public static IConfigurationBuilder AddMyConfiguration(this IConfigurationBuilder configurationBuilder, IDictionary<string, string> data) { return configurationBuilder.Add<MyConfigurationSource>(source => { source.Data = data; }); } }
如下调用
class Program { static void Main(string[] args) { var builder = new ConfigurationBuilder(); builder.AddMyConfiguration(new Dictionary<string, string>() {{"Name", "Test"}}); var configuration = builder.Build(); var value = configuration["name"]; Console.WriteLine(value); Console.Read(); } }
上面简单介绍了如何自定义自己的配置,掌握原理方法,可以根据具体需求实现自己的配置源