我有两个Net Core API控制器:RealController
和MockController
,我想基于哪个控制器接受请求在应用程序中注入差异服务。
例如,如果请求被RealController
接受,我想在所有需要的类中注入RealSharedService
(作用域),但是如果请求被MockController
接受,我而是要注入MockSharedService
。
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
{
....
}
答案 0 :(得分:2)
您可以使用HttpContextAccessor有条件地解析您的服务:
services.AddHttpContextAccessor();
services.AddScoped<ISharedService>(sp => {
var httpContext = sp.GetService<IHttpContextAccessor>().HttpContext;
Endpoint endpoint = httpContext.Features.Get<IEndpointFeature>()?.Endpoint;
if (endpoint.DisplayName.Contains("MockController"))
{
return new MockService();
}
else
{
return new RealService();
}
});