针对不同API控制器Autofac的服务接口的多种实现

时间:2018-08-14 14:34:09

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

我有许多具有IService和ILog接口的api控制器,还有一些作为构造函数参数。

IService具有不同的实现:

public interface IService
{
   void Process();
}

DefaultService:IService CallService:IService

我创建了两个api控制器 DefaultController CallController

[Route("api/[controller]")]
[ApiController]
public class DefaultController : ControllerBase
{
   private readonly IService _defaultService;
   private readonly ILog _log;

   public DefaultController(IService defaultService, ILog log, .... other parameters)
   {
      _defaultService = defaultService;
      _log = log;
   }
}

[Route("api/[controller]")]
[ApiController]
public class CallController: ControllerBase
{
   private readonly IService _callService;
   private readonly ILog _log;

   public CallController(IService callService, ILog log,.... other parameters)
   {
      _callService = callService;
      _log = log;
   }
}

我想要的是,将 DefaultService注入DefaultController ,并将 CallService注入CallController

所以我尝试使用SO答案进行以下尝试,但一直给我默认答案

var builder = new ContainerBuilder();

builder.RegisterType<DefaultService>()
    .As<IService>()
    .InstancePerLifetimeScope();

builder.RegisterType<DefaultService>()
    .Named<IService>("ForDefaultController")
    .InstancePerLifetimeScope();

//updated after comment -----------
builder.RegisterType<DefaultController>()
    .WithParameter(ResolvedParameter.ForNamed<IService>("ForDefaultController"));
// -------------------


builder.RegisterType<CallService>()
    .Named<IService>("ForCallController")
    .InstancePerLifetimeScope();

builder.RegisterType<CallController>()
    .WithParameter(ResolvedParameter.ForNamed<IService>("ForCallController"));

那我该怎么办?

如果需要示例项目,则可以克隆this github存储库。

0 个答案:

没有答案