tags:

views:

768

answers:

2

How to use this funcionality in ninject 2.0?

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

The "With" isn't there :(

A: 

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.

Adrian Grigore
Thanks for the answer, but unfortunately I can't call the constructor of my object without this parameter... Ninject 1.x does the job pretty well, I would like to know how this feature changed in the 2.0 version.
andrecarlucci
+20  A: 
   [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 );
   }
Ian Davis