在 Web API 应用程序中,我有两个控制器,MyAController 和 MyBController,每个都依赖于 IMyService,但配置不同:
public class MyAController : ApiController
{
private readonly IMyService service;
public MyAController(IMyService service)
{
this.service = service;
}
}
public class MyBController : ApiController
{
private readonly IMyService service;
public MyBController(IMyService service)
{
this.service = service;
}
}
public interface IMyService
{
}
public class MyService : IMyService
{
private readonly string configuration;
public MyService(string configuration)
{
this.configuration = configuration;
}
}
我尝试通过以下方式配置 DryIoc:
private enum ServiceKeyEnum
{
ServiceA,
ServiceB
}
container.RegisterInstance("configurationA", serviceKey: "CONFIGURATIONA");
container.RegisterInstance("configurationB", serviceKey: "CONFIGURATIONB");
container.Register<IMyService, MyService>(Reuse.Singleton, Made.Of(() => new MyService(Arg.Of<string>("CONFIGURATIONA"))), serviceKey: ServiceKeyEnum.ServiceA);
container.Register<IMyService, MyService>(Reuse.Singleton, Made.Of(() => new MyService(Arg.Of<string>("CONFIGURATIONB"))), serviceKey: ServiceKeyEnum.ServiceB);
container.Register<MyAController>(Reuse.InResolutionScope, made: Parameters.Of.Details((r, p) => ServiceDetails.IfUnresolvedReturnDefault).Type<IMyService>(serviceKey: ServiceKeyEnum.ServiceA));
container.Register<MyBController>(Reuse.InResolutionScope, made: Parameters.Of.Details((r, p) => ServiceDetails.IfUnresolvedReturnDefault).Type<IMyService>(serviceKey: ServiceKeyEnum.ServiceB));
如果我尝试使用以下方法调用解决方案:
var controllerA = container.Resolve<MyAController>();
var controllerB = container.Resolve<MyBController>();
我得到了两个分别配置了 configurationA 和 configurationB 的控制器。但是,当我尝试使用 REST 调用调用 api 时,出现以下错误:
An error occurred when trying to create a controller of type 'MyAController'. Make sure that the controller has a parameterless public constructor.
所以我想,我需要以不同的方式注册控制器......但是如何?
任何帮助将不胜感激....