35

How to use this functionality in ninject 2.0?

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

The "With" isn't there :(

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
andrecarlucci
  • 5,927
  • 7
  • 52
  • 58

2 Answers2

66
   [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 );
   }
Ryan Lundy
  • 204,559
  • 37
  • 180
  • 211
Ian Davis
  • 3,848
  • 1
  • 24
  • 30
  • 1
    Can I pass parameters to an object deeply in the object graph using ResolveAtGet? – Zach May 29 '12 at 08:48
  • The Get method calls only pass the parameters to the top level item being resolved. Other than that, if you want parameters passed to objects deeper in the chain, you would have to do that in the binding. – Ian Davis May 29 '12 at 11:01
  • @Zach (and Ian but he knows this!) there is an overload on the underlying WithConstructorArgument / ConstuctorArgumetn ctor which allow args to be marked as inherited which causes them to propagate into child Resolutions like I think you want. (In general its the wrong approach and will cause a mess but its definitely in there) – Ruben Bartelink May 29 '12 at 12:00
1

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
  • 33,034
  • 36
  • 130
  • 210
  • 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 Sep 03 '09 at 16:33