Footsteps in the sand, the seashore mind…

Ninject, Primer – Contextual Binding

I am currently learning how to use Ninject as a Inversion of Control and Dependency Injection tool.

I have created a very simple Console Application that is based on the tutorials at github. As I learn all the cool features of Ninject, I will then update my blog e.g. When I start learning about conventions and custom providers etc

My first Class File has custom attributes that I can use to apply contextual/conditional binding:

This means when we define bindings we can now have conditions based on custom attribute names which are strongly types

You do not need custom attributes you could use strings, but then you lose type safety.

Excellent, now the last part of the setup is to create a custom Ninject module. Note that when you create a module, it will not be called directly, but Ninject will detect and load it for you, when you ask it to.

ok, so lets create a module that does all the binding stuff for us, so we can keep our game code clean!

—————————————– AllFighterModule .cs——————————————–

using System;

using Ninject;

using Ninject.Modules;

namespace NinjectTutorial

{

public class AllFighterModule : NinjectModule

{

public override void Load()

{

Bind<IWeapon>().To<Sword>().WhenTargetHas<MeleeBladeAttribute>();

Bind<IWeapon>().To<Bow>().WhenTargetHas<RangeAttribute>();

Bind<IWeapon>().To<Shuriken>().WhenTargetHas<ThrowingAttribute>();

Bind<Samurai>().ToSelf();

}

}

}

—————————————–END AllFighterModule .cs——————————————–

As we can see when use the WHEN keyword to detect the decorated custom attributes and then bind the appropriate concrete class.