This is an extension to the question Why do I need an IoC container as opposed to straightforward DI code?
I've been learning Ninject and came up with the following example, the example goes through the manual way of doing DI and the Ninject way of doing DI:
class Program
{
static void Main(string[] args)
{
NinjectWay();
ManualWay();
Console.ReadKey();
}
private static void ManualWay()
{
Console.WriteLine("ManualWay***********************");
IWeapon sword = new Sword();
Samurai samurai = new Samurai(sword);
Console.WriteLine(samurai.Attack("ManualWay..."));
// change weapon
IWeapon dagger = new Dagger();
samurai.Weapon = dagger;
Console.WriteLine(samurai.Attack("ManualWay..."));
IWeapon weapon = new Shuriken();
IWarrior ninja = new Ninja(weapon);
Console.WriteLine("Manual way.. inject shuriken when a ninja. " + ninja.Weapon.Name);
IWarrior ninja2 = new Ninja(weapon);
}
private static void NinjectWay()
{
Console.WriteLine("NinjectWay***********************");
IKernel kernel = new StandardKernel();
kernel.Bind<IWeapon>().To<Sword>();
var samurai = kernel.Get<Samurai>();
Console.WriteLine(samurai.Attack("NinjectWay..."));
kernel.Rebind<IWeapon>().To<Dagger>();
samurai = kernel.Get<Samurai>();
Console.WriteLine(samurai.Attack("NinjectWay..."));
kernel.Bind<IWeapon>().To<Shuriken>().WhenInjectedInto<Ninja>();
var ninja = kernel.Get<Ninja>();
ninja.OffHandWeapon = new ShortSword();
Console.WriteLine("Conditional Injection..."+ninja.Weapon.Name);
Console.WriteLine("Conditional Injection: OffhandWeapon = " + ninja.OffHandWeapon.Name);
var ninja2 = kernel.Get<Ninja>();
Console.WriteLine("Conditional Injection..." + ninja2.Weapon.Name);
Console.WriteLine("Conditional Injection: OffhandWeapon = " + ninja2.OffHandWeapon.Name);
Console.WriteLine("");
}
}
I hear the benefits happen when the scale of the project increases but I'm not seeing it. Help me understand this better. Provide more examples in C#/Ninject and help me understand where the benefits really become apparent.