我有:
public interface ITestService{}
public class TestService : ITestService {
public TestService(IOptions<TestOptions> testOptions){
// do something with testOptions.value
}
}
并在 appsettings.json 中
{
"TestOptions1" : {
"Url": "something"
},
"TestOptions2" : {
"Url": "something"
},
}
我需要能够在控制器内注入不同的 ITestService,如果使用 appsettings.json TestOptions1 或 TestOptions2,我需要能够设置的方式有所不同。
无需对代码进行太多更改(如果有的话)即可实现此目的的最简单方法是什么? 理想情况下,我只需调用控制器来使用 TestService("TestOptions1") 或 TestService("TestOptions2")
谢谢!
您可以尝试注入 Iconfiguration 并使用字符串参数来获取相应的选项:
测试服务.cs
public class TestService
{
private TestOption testOption;
public TestService(string option, IConfiguration configuration)
{
testOption= configuration.GetSection(option).Get<TestOption>();
//You can use testOption.Url now
}
}
控制器
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly IConfiguration _configuration;
public ValuesController(IConfiguration configuration)
{
this._configuration = configuration;
}
[HttpGet("test")]
public void test()
{
var test1 =new TestService("TestOptions1",_configuration);
var test2 =new TestService("TestOptions2",_configuration);
}
}