【发布时间】:2020-08-08 01:03:46
【问题描述】:
我有两个 Net Core API 控制器:RealController 和 MockController,我想根据哪个控制器接受请求在应用程序中注入不同的服务。
例如,如果请求被RealController 接受,我想在所有需要的类中注入RealSharedService(作用域),但如果请求被MockController 接受,我想注入@987654326 @ 代替。
public class RealController : ControllerBase
{
public RealController(...)
{
//I could do somethig here to change the ISharedService intance to RealSharedService
}
}
public class MockController : ControllerBase
{
public MockController(...)
{
//I could do somethig here to change the ISharedService intance to MockSharedService
}
}
public class Service1
{
public Service1(ISharedService sharedService)
{
//The ISharedService instance must be RealSharedService or MockSharedService based on
// the request, if it was accepted by RealController or MockController
}
}
public class RealSharedService : ISharedService
{
....
}
public class MockSharedService : ISharedService
{
....
}
【问题讨论】:
-
Service1没有接口?你是怎么注射的?向控制器注入了什么?
标签: c# asp.net-core .net-core dependency-injection asp.net-core-webapi