• 在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:      }
  • 相关阅读:
    MFC 简介
    C++使用thread类多线程编程
    C++中stack
    C++中头文件简介(stdio.h & chrono)
    别人写的很好Arduino教材
    Communicating to 2 SPI Slaves with USART & SPI ports on Atmega16U2
    HDU 2089 不要62(挖个坑=-=)
    HDU 3555 Bomb(数位DP)
    HDU 3480 Division(斜率优化+二维DP)
    HDU 3045 Picnic Cows(斜率优化DP)
  • 原文地址:https://www.cnblogs.com/zbw911/p/3173512.html
Copyright © 2020-2023  润新知