在 .NET Core 中,可以给配置文件使用提供程序,例如从 JSON 或 XML文件、环境变量或命令行参数中读取配置。只需要从 NuGet 包 Microsoft.ExtensionsConfiguration 中创建一个ConfigurationBuilder,并向此构建器添加提供程序。要添加 JSON 提供程序,需要调用扩展方法 AddJsonFile。构建器的 Build 方法返回一个实现 IConfiguration 的对象。可以使用此接口通过任何已配置的提供程序来访问已配置值。下面的示例代码从配置中检索 Logging 部分,并将其传递给 RegisterServices 方法:
var configurationBuilder = new ConfigurationBuilder() ;
configurationBuilder.AddJsonFile("appsettings.json");
IConfiguration configuration = configurationBuilder.Build();
RegisterServices(configuration);
示例应用程序的配置文件根据提供程序和类别配置不同的配置值。对于 Debug 提供程序,LogLevel 设置为 Information。这样,对于所有类别,Information及以上级别都记录到 Visual Studio 的 Output 窗口。对于 Console 提供程序,LogLevel 根据类别的不同而不同。在 Console 提供程序的配置之下,所有其他提供程序的默认配置都是基于类别用特定的日志级别定义:
{
"Logging": {
"Debug": {
"LogLevel": "Information"
},
"Console": {
"LogLevel": {
"LoggingConfigurationSample.SampleController": "Information",
"Default": "Warning"
}
},
"LogLevel": {
"Default": "Warning",
"System": "Information",
"LoggingConfigurationSample.SampleController": "Warning"
}
}
}
在日志配置就绪后,现在调用 AddConfiguration 方法,以传递对IConfiguration 对象的引用。AddConfiguration 方法需要配置文件中 Logging部分的内容:
static void RegisterServices(IConfiguration configuration)
{
var services = new ServiceCollection();
services.AddLogging(builder =>
{
builder.AddConfiguration(configuration.GetSection("Logging"))
.AddConsole();
#if DEBUG
builder.AddDebug();
#endif
});
services.AddScoped<SampleControler>();
AppServices = services.BuildServiceProvider();
}
文章来源于【dotnet讲堂】