如何通过主机企业从配置对象获取值?
在.NET 6中启动了一个新的控制台应用程序,并正在添加依赖注入。在下面的代码中,如何访问ICONFIGURATION对象以从AppSettings读取值(调用构建后?
该配置在库存服务中可用,如它通过构造函数注入,但是如果我想从AppSettings读取值在program.cs中的代码中,我该如何了解
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();
Started a new Console app in .NET 6 and am adding Dependency Injection. In the code below, how can I get access to the IConfiguration object to read a value from appsettings (after calling Build?
The configuration is available within the StoreFactory service, as its injected via the constructor, but if I want to read values from appsettings within the main section of code within program.cs, how can I get at it?
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
host.CreatedEfaultBuilder
定义了发现JSON配置并通过ICONFIGURATION
实例将其公开的行为。从主机
实例中,您可以向服务提供商询问iconfiguration
实例,然后询问值。有关更多信息,请阅读 docs 。
The
Host.CreateDefaultBuilder
defines the behavior to discover the JSON configuration and expose it through theIConfiguration
instance. From thehost
instance, you can ask the service provider for theIConfiguration
instance and then ask it for values.For more information read the Docs.