Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With.Parameters.ConstructorArgument with ninject 2.0

Tags:

c#

ninject

How to use this functionality in ninject 2.0?

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

The "With" isn't there :(

like image 217
andrecarlucci Avatar asked Sep 03 '09 15:09

andrecarlucci


2 Answers

   [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 );    } 
like image 77
Ian Davis Avatar answered Sep 22 '22 01:09

Ian Davis


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.

like image 27
Adrian Grigore Avatar answered Sep 22 '22 01:09

Adrian Grigore