I've recently been trying to learn IoC, and have a couple questions based on the following code:
public class WarriorModule : NinjectModule
{
public override void Load()
{
Bind<IWeapon>().To<Sword>();
Bind<Samurai>().ToSelf();
}
}
I'm having trouble grasping the new concept of interfaces. Before I would create an interface such as IRunnable
, implementing the function void Run()
. With IoC, I'm now viewing an interface as something that only maps to a single concrete class. Assuming that, how would I map multiple concrete classes to an interface? I keep reading that you can map multiple interfaces to a single concrete class, but not the other way around (unless this is where contextual mapping comes into play).
Assuming interfaces only map to a single object, when should I create an interface as opposed to having an object bind to itself? Either way you will have to change the same piece of code when a mapping changes correct?
Edit: I marked the answer I did because it helped me personally. Both comments are equally informative though.
A good IoC container should not change the way interfaces are used:
Ninject allows using interfaces this way using two different concepts:
Conditional bindings: If several classes implement the same interface you have to specify which implementation is used in which case. This is done using conditions:
Bind<IWeapon>().To<Sword>().When(ctx => TodayIsSunday());
Bind<IWeapon>().To<Dagger>().When(ctx => !TodayIsSunday());
Multiple Interfaces: See my blogpost http://www.planetgeek.ch/2010/12/08/ninject-extension-contextpreservation-explained/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With