在。net 6中启动了一个新的控制台应用程序,并添加了依赖注入。在下面的代码中,我如何访问IConfiguration对象以从appsettings读取值(在调用Build之后)?
配置在StoreFactory服务中可用,因为它通过构造函数注入,但是如果我想从program.cs中代码的主要部分中的appsettings中读取值,我怎么才能得到它?
program.cs
var SvcBuilder = new HostBuilder()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(Directory.GetCurrentDirectory());
config.AddJsonFile("appsettings.json", optional: true);
config.AddEnvironmentVariables();
if (args != null)
{
config.AddCommandLine(args);
}
})
.ConfigureServices((hostContext, services) =>
{
services.AddLogging(configure => configure.AddConsole())
.AddTransient<IStoreFactory, StoreCtxFactory>();
});
var host = SvcBuilder.Build();
Host.CreateDefaultBuilder
定义了发现JSON配置并通过IConfiguration
实例公开它的行为。在host
实例中,可以向服务提供商查询IConfiguration
实例的值。
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using IHost host = Host.CreateDefaultBuilder(args).Build();
// Ask the service provider for the configuration abstraction.
IConfiguration config = host.Services.GetRequiredService<IConfiguration>();
// Get values from the config given their key and their target type.
var configValueInt = config.GetValue<int>("yourKeyName");
string configValueStr = config.GetValue<string>("yourKeyName");
更多信息请参阅文档。