Question

I'm new to Ninject, after do some research, I came up with an example:

public interface IWeapon
{
    void Hit(Target target);
}

public class Sword : IWeapon
{
    public void Hit(Target target)
    {
        //do something here
    }
}

public class Character
{
    private IWeapon weapon;

    public Character(IWeapon weapon)
    {
        this.weapon = weapon;
    }

    public void Attack(Target target)
    {
        this.weapon.Hit(target);
    }
}

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

public void Main()
{
    Target sometarget = new Target();
    Kernel kernel = new StandardKernel(new Bindings());
    var weapon = kernel.Get<IWeapon>();
    var character = new Character(weapon);
    character.Attack(sometarget);
}

As you can see, in order to resolve the dependency, I have to pull instance of IWeapon using Kernel and pass it to Character's constructor. I think this somehow ugly, I wonder is there a way that I can directly pull instance of Character and Ninject will automatically resolve the dependency with IWeapon? Something like:

Character character = kernel.Resolve<Character>();
Was it helpful?

Solution

By default Ninject will allow you to auto resolve concrete types with the correct bindings. In you instance you could just do:

public void Main()
{
    Target sometarget = new Target();
    IKernel kernel = new StandardKernel(new Bindings());
    //var weapon = kernel.Get<IWeapon>();
    var character = kernel.Get<Character>();
    character.Attack(sometarget);
}

For more information read through the Ninject wiki: https://github.com/ninject/ninject/wiki/Dependency-Injection-With-Ninject

OTHER TIPS

You haven't registered Character. Create an ICharacter interface and Bind it to the Character class as well. Then when you attempt to resolve the ICharacter, Ninject will see that it needs an instance of IWeapon for the Character constructor and it will get one that is registered to that interface.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top