在Ninject 向构造参数中注入具有相同类型的参数
实际上这个有多种解决方法,加自定义Attribute,或Named(),但这些方式有一些侵入性,Named,要引用Ninject, 自定义Attribute,还要还要再写几行代码吗,所以使用下面的方法,
public class All
{
private readonly II _a;
private readonly II _b;
public All( II a, II b)
{
_a = a;
_b = b;
}
public void Print()
{
Console.WriteLine(_a.get());
Console.WriteLine(_b.get());
}
}
public interface II
{
string get();
}
class A : II
{
public string get()
{
return "a";
}
}
class B : II
{
public string get()
{
return "b";
}
}
1: [TestClass]
2: public class UnitTest1
3: {
4: [TestMethod]
5: public void TestMethod1()
6: {
7: var ker = new Ninject.StandardKernel();
8:
9: //ker.Bind<II>().To<A>().Named("a");
10: //ker.Bind<II>().To<A>().When(x=>x);
11: ker.Bind<II>().To<A>().When(x => x.Target.Name == "a");
12:
13: ker.Bind<II>().To<B>().When(x => x.Target.Name == "b");
14:
15: //ker.Bind<All>().To<All>().WithConstructorArgument("a", new A()).WithConstructorArgument("b", new B());
16:
17: var all = ker.Get<All>();
18:
19: all.Print();
20: }
21: }