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>();