My preferred approach to using contextual binding is to define a default binding first:
If you don’t like attributes and never make typing mistakes (I suppose it’s also useful when you can’t modify the source code) there is also a name-based binding:
Since one code snippet is worth 500 words here’s the entire unit test I wrote. This both demonstrates the conditional binding and starts to give you a flavor of how Ninject can simplify your code once the container wiring is done.
One Gotcha (well it got me anyway) I’m in the process of refactoring an actual project towards Ninject so I’m probably doing some unusual things along the way. One thing I was doing was the equivalent of directly getting an IAttackAbility in code: Prior to using a contextual binding (that is I only had IAttackAbility mapped directly to StrongAttack) this code would work fine. Once I add contextual binding this code will throw a NullReferenceException. You can see a screencast demonstrating this behavior . I’m not sure I understand exactly why, but I’m surmising that once I add the WhenTargetHas clause, I must be injecting into a target that the Ninject context is already aware of. In this case Ninject doesn’t know anything about my_attack_ability and therefore when it tries to evaluate the WhenTargetHas clause it throws.
UPDATE- I have been communicating with Ian Davis and the gotcha behavior was a bug that he fixed on 10/22/2009. TestNoTargetThrows now fails, which is a good thing. I got rid of it and replaced it with the test below.