andrecarlucci
andrecarlucci

Reputation: 6296

With.Parameters.ConstructorArgument with ninject 2.0

How to use this functionality in ninject 2.0?

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

The "With" isn't there :(

Upvotes: 35

Views: 13295

Answers (2)

Ian Davis
Ian Davis

Reputation: 3868

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

Upvotes: 66

Adrian Grigore
Adrian Grigore

Reputation: 33318

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.

Upvotes: 1

Related Questions