配置相关的几个对象:Configuration、ConfigurationBuilder和ConfigurationSource、ConfigurationProvider。
Configuration对象承载着配置信息;
ConfigurationProvider则是配置信息原始数据源的提供者;
两者之间沟通由ConfigurationBuilder来完成,它利用ConfigurationProvider提取源数据将其转换为Configuration对象。
使用文本文件做数据源
public class PropertiesConfigurationSource : IConfigurationSource
{
public string Path { get; set; }
public PropertiesConfigurationSource(string path)
{
this.Path = path;
}
public IConfigurationProvider Build(IConfigurationBuilder builder)
{
return new PropertiesConfigurationProvider(this.Path);
}
}
public class PropertiesConfigurationProvider : ConfigurationProvider
{
public string Path { get; set; }
public PropertiesConfigurationProvider(string path)
{
this.Path = path;
}
public override void Load()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
string[] lines = File.ReadAllLines(this.Path);
string[] pair = null;
foreach (var line in lines)
{
if (!string.IsNullOrWhiteSpace(line))
{
pair = line.Split('=');
if (pair.Length == 2)
{
dict.TryAdd(pair[0], pair[1]);
}
}
}
this.Data = dict;
}
}
public static class ConfigurationBuilderExtension
{
public static IConfigurationBuilder AddPropetiesFile(this IConfigurationBuilder configurationBuilder, string path)
{
configurationBuilder.Add(new PropertiesConfigurationSource(path));
return configurationBuilder;
}
}
未完待续...