在Ninject 向构造参数中注入具有相同类型的参数

时间:2023-03-09 09:11:28
在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";
        }
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

   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:      }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

相关文章