.NET Core配置文件加载与DI注入配置数据

时间:2023-03-08 19:56:35

.NET Core配置文件

在以前.NET中配置文件都是以App.config / Web.config等XML格式的配置文件,而.NET Core中建议使用以JSON为格式的配置文件,因为使用起来更加方面灵活,而且可以使用.NET Core中的DI注入配置数据。

使用:

             var config = new ConfigurationBuilder()
.AddInMemoryCollection() //将配置文件的数据加载到内存中
.SetBasePath(Directory.GetCurrentDirectory()) //指定配置文件所在的目录
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) //指定加载的配置文件
.Build(); //编译成对象
Console.WriteLine(config["test"]); //获取配置中的数据
config["test"] = "test test"; //修改配置对象的数据,配置对象的数据是可以被修改的
Console.WriteLine(config["test11"]); //获取配置文件中不存在数据也是不会报错的
Console.WriteLine(config["theKey:nextKey"]); //获取:theKey -> nextKey 的值

配置文件appsettings.json文件内容:

 {
"test": "testVal",
"theKey": {
"nextKey": "keyVal"
}
}

注意:

ConfigurationBuilder需要添加包:"Microsoft.Extensions.Configuration"

AddJsonFile需要添加包:"Microsoft.Extensions.Configuration.Json"

与DI配合使用

             var sp = new ServiceCollection()
.AddOptions() //注入IOptions<T>,这样就可以在DI容器中获取IOptions<T>了
.Configure<TestCls>(config.GetSection("TestCls")) //注入配置数据
//也可以对注入的配置数据进行修改
.Configure<TestCls>(t =>
{
t.Name = "Jame"; //修改Name的值
})
.BuildServiceProvider(); //编译 var test = sp.GetService<IOptions<TestCls>>(); //获取注入的配置数据对象
Console.WriteLine(JsonConvert.SerializeObject(test.Value)); //{"Name":"Jame","Age":123} //下面的代码中检验Configure注入的配置数据对象是单例模式的(.NET Core中DI容器的三种生命周期:Singleton(单例), Scoped(作用域), Transient(瞬态))
var test1 = sp.GetService<IOptions<TestCls>>();
Console.WriteLine(test == test1); //true
//创建一个新的作用域获取配置数据对象
var test2 = sp.GetService<IServiceScopeFactory>().CreateScope().ServiceProvider.GetService<IOptions<TestCls>>();
Console.WriteLine(test == test2); //true

配置测试类:

         public class TestCls
{
public string Name { get; set; }
public int Age { get; set; }
}

appsettings.json中的内容:

 {
"TestCls": {
"Name": "Tom",
"Age":
}
}

注意:

ServiceCollection需要添加包: "Microsoft.Extensions.DependencyInjection"

AddOptions需要添加包: "Microsoft.Extensions.Options.ConfigurationExtensions"

ASP.NET Core中使用

Startup.cs -> Startup构造方法中进行初始化配置文件:

             var builder = new ConfigurationBuilder()
.AddInMemoryCollection()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
Configuration = builder.Build();

Startup.cs -> ConfigureServices方法中进行注入配置数据:

             services.AddOptions()        //注入IOptions<T>
.Configure<TestCls>(Configuration.GetSection(nameof(TestCls)))
.Configure<TestCls>(test =>
{
test.Name = "Jame"; //修改Name的值
});

配置文件中的配置数据:

 {
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"TestCls": {
"Name": "Tom",
"Age":
}
}

注入到控制器中:

     [Route("api/[controller]")]
public class ValuesController : Controller
{
IOptions<TestCls> _test;
public ValuesController(IOptions<TestCls> test)
{
_test = test;
}
[HttpGet]
public string Gets()
{
return JsonConvert.SerializeObject(_test.Value);
}

访问:/api/values

显示:{"Name":"Jame","Age":123}