每个请求覆盖依赖项注入

时间:2020-08-08 01:03:46

标签: c# asp.net-core .net-core dependency-injection asp.net-core-webapi

我有两个Net Core API控制器:RealControllerMockController,我想基于哪个控制器接受请求在应用程序中注入差异服务。

例如,如果请求被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
{
    ....
}

1 个答案:

答案 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();
   }
});