使用DI读取配置,读取时声明类型有IOptions<T>、IOptionsMonitor<T>、IOtionsSnapshot<T>类型,推荐使用最后一种。
要读取的配置文件 jsconfig.json 如下,把属性改成始终复制。
{ "Name": "wzh", "addr": "beijing", "Teacher": { "Name": "zhangsan", "Age": 45 } }
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using System; using System.Linq; namespace ConsoleApp8 { class Program { static void Main(string[] args) { IServiceCollection service = new ServiceCollection(); service.AddScoped<Demo1>(); service.AddScoped<Demo2>(); ConfigurationBuilder configbuilder = new ConfigurationBuilder(); configbuilder.AddJsonFile("jsconfig.json", optional: false, reloadOnChange: false); var root = configbuilder.Build(); service.AddOptions() .Configure<Student>(x => root.Bind(x)) .Configure<Teacher>(x=>root.GetSection("Teacher").Bind(x)); using (var sp=service.BuildServiceProvider()) { var demo1=sp.GetRequiredService<Demo1>(); var demo2= sp.GetRequiredService<Demo2>(); demo1.Test(); demo2.Test(); } Console.WriteLine("Hello World!"); } } public class Demo1 { private readonly IOptionsSnapshot<Student> config; public Demo1(IOptionsSnapshot<Student> config) { this.config = config; } public void Test() { Console.WriteLine("学生"); Console.WriteLine(config.Value.Name); Console.WriteLine(config.Value.Addr); } } public class Demo2 { private readonly IOptionsSnapshot<Teacher> config; public Demo2(IOptionsSnapshot<Teacher> config) { this.config = config; } public void Test() { Console.WriteLine("老师"); Console.WriteLine(config.Value.Name); Console.WriteLine(config.Value.Age); } } public class Student { public string Name { get; set; } public string Addr { get; set; } } public class Teacher { public string Name { get; set; } public int Age { get; set; } } }