延续上一篇文章,这篇文章新增一个Ini文件配置提供者,并从注入环境变量配置修改为注入Ini配置的步骤,让大家体验下依赖注入的便捷
Ini配置:
class IniConfigProvider : IConfigProvider { public string Path { get; set; } public string GetValue(string Name) { var keyValues= File.ReadAllLines(Path).Select(x => x.Split('=')).Select(x => new { Name = x[0], Value = x[1] }); var keyValue= keyValues.Where(x => x.Name == Name).SingleOrDefault(); return keyValue!=null?keyValue.Value : string.Empty; } } public static class ConfigProviderExtensions { public static void AddEnvVarConfig(this IServiceCollection services) { services.AddScoped<IConfigProvider, EnvVarConfigProvider>(); } /// <summary> ///注册Ini配置提供者 /// </summary> /// <param name="services"></param> public static void AddIniConfig(this IServiceCollection services,string path) { //因为IniConfigProvider需要初始化Path,所以使用AddScoped(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory)这个重载 services.AddScoped<IConfigProvider>(x => new IniConfigProvider() { Path = path }); } }
在MailServicesConsole中添加ini文件(config.ini),ini内容如下:
[email protected] User=Tony Password=123456
Main函数修改如下:
static void Main(string[] args) { ServiceCollection services = new ServiceCollection(); services.AddLog(); // services.AddEnvVarConfig(); services.AddIniConfig("config.ini"); services.AddMail(); using(ServiceProvider sp=services.BuildServiceProvider()) { IMailSender mailSender = sp.GetRequiredService<IMailSender>(); mailSender.Send("[email protected]", "Lily", "hello,Nice to meet you"); } }
输出:
可以看到,当更换一个配置提供者时,只需要增加一个配置提供者的具体实现,并通过扩展方法把配置提供者注册到容器,用户只需要从.AddEnvVarConfig()改为.AddIniConfig()即可
标签:string,案例,提供者,services,static,Path,组件,DependencyInjection,public From: https://www.cnblogs.com/luohualiushui1173/p/17911493.html