【问题标题】:Override Dependency Injection per request覆盖每个请求的依赖注入
【发布时间】: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


【解决方案1】:

您可以使用 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();
   }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 2018-06-19
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多