Can someone explain dependency injection with a basic .NET example and provide a few links to .NET resources to extend on
Ninject must have one of the coolest sample out there: (pieced from the sample)
interface IWeapon {
void Hit(string target);
}
class Sword : IWeapon {
public void Hit(string target) {
Console.WriteLine("Chopped {0} clean in half", target);
}
}
class Shuriken : IWeapon {
public void Hit(string target) {
Console.WriteLine("Shuriken tossed on {0}", target);
}
}
class Samurai {
private IWeapon _weapon;
[Inject]
public Samurai(IWeapon weapon) {
_weapon = weapon;
}
public void Attack(string target) {
_weapon.Hit(target);
}
}
class WeaponsModule: NinjectModule {
private readonly bool _useMeleeWeapons;
public WeaponsModule(bool useMeleeWeapons) {
_useMeleeWeapons = useMeleeWeapons;
}
public void Load() {
if (useMeleeWeapons)
Bind().To();
else
Bind().To();
}
}
class Program {
public static void Main() {
bool useMeleeWeapons = false;
IKernel kernel = new StandardKernel(new WeaponsModule(useMeleeWeapons));
Samurai warrior = kernel.Get();
warrior.Attack("the evildoers");
}
}
This, to me, reads very fluently, before you start up your dojo you can decide how to arm your Samurais.