tags:

views:

159

answers:

1

Hi,

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>();
+1  A: 

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.

Joseph
got it - thanks - can I ask, if I actually wanted to access Samurai as various points in my code (in fact instead of Samurai if this was my DataAccessLayerFacade) should I then think about using the Object Scopes like "Bind<Shogun>().ToSelf().InSingletonScope();" which is discussed at http://wiki.github.com/enkari/ninject/object-scopes?
Greg
@Greg it all depends on what you want the object lifetime to be for that particular object. For example, if you only want to have one samurai object, and you want to get that object any time you ask for an IWarrior, then you'd want to do something like Bind<IWarrior>().To<Samurai>().InSingletonScope(); However, in most cases that's not the object lifecycle you want. What you want is Transient (which is the default) where you create a new object each time to ask the Kernel to resolve.
Joseph