Tutorial :How do I setup NInject? (I'm getting can't resolve “Bind”, in the line “Bind().To();”)



Question:

I'm getting confused in the doco how I should be setting up Ninject. I'm seeing different ways of doing it, some v2 versus v1 confusion probably included...

Question - What is the best way in my WinForms application to set things up for NInject (i.e. what are the few lines of code required). I'm assuming this would go into the MainForm Load method. In other words what code do I have to have prior to getting to:

Bind<IWeapon>().To<Sword>();  

I have the following code, so effectively I just want to get clarification on the setup and bind code that would be required in my MainForm.Load() to end up with a concrete Samurai instance?

internal interface IWeapon  {      void Hit(string target);  }    class Sword : IWeapon  {      public void Hit(string target)      {          Console.WriteLine("Chopped {0} clean in half", target);      }  }    class Samurai  {      private IWeapon _weapon;        [Inject]      public Samurai(IWeapon weapon)      {          _weapon = weapon;      }        public void Attack(string target)      {          _weapon.Hit(target);      }  }  

thanks

PS. I've tried the following code, however I can't resolve the "Bind". Where does this come from? what DLL or "using" statement would I be missing?

private void MainForm_Load(object sender, EventArgs e)  {      Bind<IWeapon>().To<Sword>();   // <==  *** CAN NOT RESOLVE Bind ***      IKernel kernel = new StandardKernel();      var samurai = kernel.Get<Samurai>();  


Solution:1

The piece that's missing here is that you have to initialize the kernel and pass in modules that you define which have the Bind in them.

So you need a module that does something like this:

public class WeaponModule: NinjectModule  {      public override void Load()      {          Bind<IWeapon>().To<Sword>();      }  }  

then in your form load instantiate the kernel like this:

private void MainForm_Load(object sender, EventArgs e)  {      IKernel kernel = new StandardKernel(new WeaponModule());      var samurai = kernel.Get<Samurai>();  

Also, if you're using Ninject 2, you don't need to have the [Inject] attribute on your constructors, Ninject figures it out by itself.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »