代码之家  ›  专栏  ›  技术社区  ›  andrecarlucci

with.parameters.constructorAgment with ninject 2.0

  •  34
  • andrecarlucci  · 技术社区  · 15 年前

    如何在Ninject2.0中使用此功能?

    MyType obj = kernel.Get<MyType>(With.Parameters.ConstructorArgument("foo","bar"));
    

    “with”不存在:(

    2 回复  |  直到 13 年前
        1
  •  66
  •   Ryan Lundy    13 年前
       [Fact]
       public void CtorArgTestResolveAtGet()
       {
           IKernel kernel = new StandardKernel();
           kernel.Bind<IWarrior>().To<Samurai>();
           var warrior = kernel
               .Get<IWarrior>( new ConstructorArgument( "weapon", new Sword() ) );
           Assert.IsType<Sword>( warrior.Weapon );
       }
    
       [Fact]
       public void CtorArgTestResolveAtBind()
       {
           IKernel kernel = new StandardKernel();
           kernel.Bind<IWarrior>().To<Samurai>()
               .WithConstructorArgument("weapon", new Sword() );
           var warrior = kernel.Get<IWarrior>();
           Assert.IsType<Sword>( warrior.Weapon );
       }
    
        2
  •  1
  •   Adrian Grigore    15 年前

    我不确定Ninject是否支持它(我现在不在我的开发计算机上),但是如果其他所有的都失败了(Ninject文档还有很多需要),您可以将初始化与构造函数分开来解决您的问题:

    class MyType 
    {
       public class MyType() {}
       public class MyType(string param1,string param2){Init(param1,param);}
       public void Init(string param1,param2){...}
    }
    

    然后你可以这样做:

    MyType obj = kernel.Get<MyType>();
    obj.Init("foo","bar");
    

    这远非完美,但在大多数情况下都应该做到。