1

我有 2 个这样定义的构造函数:

public interface IMyService<T1,T2>{}
public class MyService1 : IMyService<SomeTypeA,SomeTypeB>
{
    public MyService2(string serviceAUri,IServiceB svc){}
    public MyService2(IServiceA svc,IServiceB svc){}

}
public class MyService2 : IMyService<SomeTypeC,SomeTypeD>
{
    public MyService2(string serviceAUri,IServiceB svc){}
    public MyService2(IServiceA svc,IServiceB svc){}

公共 MyService2(IServiceC svc,IServiceD svc){} }

我在 T1 和 T2 的不同值上注册 IMyService 的多个服务实现,因此注册机制必须在接口的实现中是通用的。

如何在不使用 [Inject] 属性的情况下指定要调用的构造函数?是否有一些我可以在“绑定”中指定的约定来指导 Ninject 选择带有“url”参数的构造函数而不是其他的?

4

1 回答 1

2

I recommend not to have multiple constructors. The only situation I can think of where this is relevant is if you are not the owner of the class. E.g. injecting a .NET library class somewhere. In that rare case you can define the constructor using the ToConstructor overload:

int someConstantValue = 1;
Func<int> someOtherValue = () => Random(10);
Bind<IFoo>.ToConstructor(c => new Foo(c.Inject<IBar>(), someConstantValue, someOtherValue, c.Inject<IBaz>());
于 2013-03-28T15:37:01.800 回答