上篇文章的讲解,配置文件可以转换成实体类,这篇文章讲解如何通过选项方式结合依赖注入进行配置
目的:实体类可以通过依赖注入获取配置文件映射的实体类
1)安装Nuget包:Microsoft.Extensions.Options
2)配置Json文件于实体类的映射并注册到容器中
3)实体类通过构造函数注入配置类,有3种方式:
IOption:不实时更新(配置文件更新,映射的实体不更新)
IOptionMonitor:瞬时更新(配置文件更新,映射的实体马上更新)
IOptionSnapShot:在一个scope内保持一致,推荐使用
下面讲解代码:
webConfig.json配置文件
{ "Name": "yxh", "Age": "18", "Proxy": {"Address": "yxh.com","Port": "80"} }
映射的实体类,WebConfig对应配置文件的根节点,Proxy对应配置文件的Proxy对象
public class WebConfig { public string Name { get; set; } public string Age { get; set; } public Proxy Proxy { get; set; } public override string ToString() { return $"Name:{Name},Age:{Age},{Proxy.ToString()}"; } } public class Proxy { public string Address { get; set; } public string Port { get; set; } public override string ToString() { return $"Address:{Address},Port:{Port}"; } }
Test1Mode是注入了Proxy的实体类,Test2Mode是注入了WebConfig的实体类
public class Test1Model { private readonly IOptionsSnapshot<Proxy> optionsSnapshot; public Test1Model(IOptionsSnapshot<Proxy> optionsSnapshot) { this.optionsSnapshot = optionsSnapshot; } public void Test() { Proxy proxy= this.optionsSnapshot.Value; Console.WriteLine(proxy.ToString()); } } public class Test2Model { private readonly IOptionsSnapshot<WebConfig> _snapshot; public Test2Model(IOptionsSnapshot<WebConfig> snapshot) { _snapshot = snapshot; } public void Test() { WebConfig config = _snapshot.Value; Console.WriteLine(config.ToString()) ; } }
Main函数如下:
static void Main(string[] args) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.AddJsonFile("webconfig.json", false, true); IConfigurationRoot configurationRoot = builder.Build(); ServiceCollection services = new ServiceCollection(); services.AddScoped<Test1Model>(); services.AddScoped<Test2Model>(); //配置JSon中的部分对象与IConfigurationRoot的映射 services.AddOptions().Configure<Proxy>(e => configurationRoot.GetSection("Proxy").Bind(e)); //配置Json的根对象与IConfigurationRoot的映射 services.AddOptions().Configure<WebConfig>(e => configurationRoot.Bind(e)); while (true) { using (var scope = services.BuildServiceProvider()) { var test1 = scope.GetRequiredService<Test1Model>(); test1.Test(); Console.ReadKey(); var test2 = scope.GetRequiredService<Test2Model>(); test2.Test(); } Console.ReadKey(); } }
标签:02,实体类,string,配置文件,C#,public,Proxy,services,Options From: https://www.cnblogs.com/yxh33/p/17900464.html