35
votes

How to use this functionality in ninject 2.0?

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

The "With" isn't there :(

2

2 Answers

66
votes
   [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 );
   }
1
votes

I'm not sure if Ninject supports it (I'm currently away from my development computer), but if all else fails (the Ninject documentation leaves a lot to be desired) you could separate initialization from the constructor to solve your problem:

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

Then you can do this:

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

It's far from perfect, but should do the job in most cases.