我想在配置依赖注入之前/在我的服务集合上调用"Build(("之前从我的 json 配置文件中获取一个值。
如果我想根据 json 配置文件中的值以不同的方式配置服务,我将如何做到这一点?
另一种表达方式是如何从 IConfigurationRoot 实现中获取配置值?
在此代码中,如何根据配置文件中的值设置"useService1"的值?
class Program
{
static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var serviceCollection = new ServiceCollection();
var useService1 = true; // how do I get a value from my configuration file here?
if (useService1)
serviceCollection.AddSingleton<IMyService>(new Service1());
else
serviceCollection.AddSingleton<IMyService>(new Service1());
var serviceProvider = serviceCollection.BuildServiceProvider();
var myService = serviceProvider.GetService<IMyService>();
myService.DoWork();
}
interface IMyService
{
void DoWork();
}
class Service1 : IMyService
{
public void DoWork()
{
Console.WriteLine("1 doing work");
}
}
class Service2 : IMyService
{
public void DoWork()
{
Console.WriteLine("2 doing work");
}
}
}
我能够使用分号来指定嵌套值来获取嵌套的appsettings.json配置值。
appsettings.json:
{
"TopLevel1": "Value1",
"TopLevel2": {
"SecondLevel1": "Value2",
"SecondLevel2": {
"ThirdLevel": "Value3"
}
}
}
class Program
{
static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var value1 = configuration["TopLevel1"];
var value2 = configuration["TopLevel2:SecondLevel1"];
var value3 = configuration["TopLevel2:SecondLevel2:ThirdLevel"];
}
}