Skip to content
bartelink edited this page Mar 17, 2011 · 39 revisions

One of the more powerful (and complex) features of Ninject is its contextual binding system. We mentioned earlier that you can register more than one binding for a type. There are two primary reasons one might want to register multiple type bindings:-

1. Multiple bindings – for Multi-Injection

This mechanism allows you to get a set of related service implementations at the same time. You use this mechanism by requesting a IEnumerable<>, T[] array or List<T> in the target – see Multi-injection

class Warrior {
    readonly IEnumerable<IWeapon> _weapons;
    public Warrior( IEnumerable<IWeapon> weapons)
    {
        _weapons=weapons;
    }
    public void Attack(string victim) {
        foreach(var weapon in _weapons) 
            Console.WriteLine(weapon.Hit(victim));
    }
}

2. Multiple bindings – for contextual binding taking the context into consideration

In this case, the appropriate implementation that should be used depends on the target context for which the service type is being resolved and the binding metadata on each binding. Up until this point, we’ve only been talking about default bindings — bindings that are used unconditionally, in any context. However, unless you make one or more of the bindings conditional, you’ll get an exception at runtime indicating that the appropriate binding to use in a given context is ambiguous (you’ll run into the same case if you do a kernel.Get<T>() and there are multiple possible results for the given service type T).

Basic constrained binding: Named bindings

Named bindings are the simplest (and most common) form of conditional binding, and are used as follows:

  1. In your type bindings, you register multiple type bindings for the same service type, but add binding metadata so you’ll be able to indicate which one is appropriate in your condition later:-
Bind<IWeapon>().To<Shuriken>().Named("Strong");
Bind<IWeapon>().To<Dagger>().Named("Weak");

2. At the target location, you indicate the name you want to use in the given context:-

class WeakAttack {
    readonly IWeapon _weapon;
    public([Named("Weak") IWeapon weakWeapon)
        _weapon = weakWeapon;
    }
    public void Attack(string victim){
        Console.WriteLine(_weapon.Hit(victim));
    }
}

3. alternately, you can programmatically achieve the same effect directly (aka Service Location antipattern) by doing:

kernel.Get<IWeapon>("Weak");

Generalized Constrained Resolution (via type bindings and/or target constraint attributes)

The Named Bindings in the previous section are built-in and have associated overloads and attribute types for a very simple reason – they’re a very common use case that can often satisfy the requirements of most straightforward applications. However they’re just a specific application of a more general concept: Constrained Resolution.

Constrained resolution involves the following elements:

  • binding metadata: extra information we include in a type binding
  • the target context: the receiver for which where the service is being resolved for
  • One or mode of the following
    1. constraint predicates on the target using the binding metadata to take into consideration when matching a resolution target against a set of bindings
    2. constraints on the type binding which take into account the target context

Constraining the binding selection via ConstraintAttribute-derived attributes on the injection target

ConstraintAttribute is an abstract attribute class from which one can derive your own constraints which filter the set of eligible bindings for injection into a target. Example usage is as follows:

// will work just as well without this line, but it's more correct and important for IntelliSense etc.
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true, Inherited = true)]
public class Swimmer : ConstraintAttribute {
    public bool Matches(IBindingMetadata metadata) {
        return metadata.Has("CanSwim") && metadata.Get<bool>("CanSwim");
    }
}
class WarriorsModule : Ninject.Modules.NinjectModule {
    public override void Load() {
        Bind<IWarrior>().To<Ninja>();
        Bind<IWarrior>().To<Samurai>().WithMetadata("CanSwim", false);
        Bind<IWarrior>().To<SpecialNinja>().WithMetadata("CanSwim", true);
    }
}
class AmphibiousAttack {
    public AmphibiousAttack([Swimmer]IWarrior warrior) {
        Assert.IsType<Samurai>(warrior);
    }
}

The above is a basic example of using the metadata to guide the selection of the appropriate binding. Here are some other examples:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true, Inherited = true)]
public class NonSwimmer : ConstraintAttribute {
    public bool Matches(IBindingMetadata metadata) {
        return metadata.Has("CanSwim") && !metadata.Get<bool>("CanSwim");
    }
}
class OnLandAttack {
    public OnLandAttack([NonSwimmer]IWarrior warrior) {
        Assert.IsType<SpecialNinja>(warrior);
    }
}

If Conditionals don’t identify a matching binding, the default binding will be used:- (TODO: fact verification)

class JustAttack {
    public JustAttack(IWarrior warrior) {
        Assert.IsType<Ninja>(warrior);
    }
}

Note that one is allowed to have multiple attributes on a target – e.g., you can combine the built-in [Named("X")] with a custom constraint such as [CanSwim] above and it’ll And the two conditions together.

Specifying constraints on the type binding using the built-in attribute-based helpers

An important point about previous section regarding Attribute driven constraints at the target site is that a sensible default approach is to use Constructor Injection and not have any container-dependencies in your business logic unless you have a really good reason. This is why constraints are more typically specified alongside the type bindings, although Ninject doesn’t mind either way – it’ll even let you constrain from the target side and the type binding side at the same time. Examples of constraints on a type binding are (specifying the same constraints as the previous section but on the bindings instead):

Bind<IWarrior>().To<Samurai>().WhenInjectedInto(typeof(OnLandAttack));
Bind<IWarrior>().To<SpecialNinja>().WhenInjectedInto(typeof(AmphibiousAttack));

There are a multiple constraint options, all specified via a When... option at the end of the type binding. The simplest form are ones driven by straightforward marker attributes, without any need to derive from base classes etc.

class SwimmerNeeded : Attribute{}
class ClimberNeeded : Attribute{}

This allows one to define constraints based on any of the following:

  1. the Target: the parameter being injected into
  2. the Member: the property, method or constructor itself
  3. the Class: the class Type within which the Member or Target is defined within
class WarriorsModule : Ninject.Modules.NinjectModule {
    public override void Load() {
        Bind<IWarrior>().To<Ninja>();
        Bind<IWarrior>().To<Samurai>().WhenClassHas<ClimberNeeded>();
        Bind<IWarrior>().To<Samurai>().WhenTargetHas<ClimberNeeded>();
        Bind<IWarrior>().To<SpecialNinja>().WhenMemberHas<SwimmerNeeded>();
    }
}

Then the right things will happen when one resolves services such as:

class MultiAttack {
    public MultiAttack([ClimberNeeded] IWarrior MountainWarrior) {
    }
    [Inject, SwimmerNeeded]
    IWarrior OffShoreWarrior { get; set; }
    [Inject]
    IWarrior AnyOldWarrior {get;set;}
}

[ClimberNeeded]
class MountainousAttack {
    [Inject, SwimmerNeeded]
    IWarrior HighlandLakeSwimmer { get; set; }
    [Inject]
    IWarrior StandardMountainWarrior { get; set; }
}

Specifying constraints on the type binding using arbitrary elements of the resolution request context

All of the .WhenXXX() helpers in the preceding section are just built-in specific applications of the generalized .When(Func<IRequest,bool>) method, which one can use as follows:

Bind<IWarrior>().To<Samurai>().When(request => request.Target.Member.Name.StartsWith("Climbing"));
Bind<IWarrior>().To<Samurai>().When(request => request.Target.Type.Namespace.StartsWith("Samurais.Climbing"));

As with all of Ninject, it’s highly recommended to look at the tests:- https://github.com/ninject/ninject/tree/master/src/Ninject.Test

They go through all the possibilities in detail, and are extremley short and readable – try it; you won’t regret looking and you may learn something along the way!

Specifying constraints in terms of Nested Contexts

There are .Depth, .ParentContext and .ParentRequest members on the IRequest passed to the When predicate which are used to define rules based on the hierarchy of requests in a service resolution where nesting takes place. See The Activation Process for more details on this.

Some articles on topics related to rested resolution:

  • http://www.planetgeek.ch/2010/12/08/ninject-extension-contextpreservation-explained/

The old style

WIP: This remainder of this page represents v1 style and syntax. Contextual binding has been change quite drastically since v1. While the same things (and much more are possible, this is simply no longer a good way of describing or demonstrating the capabilities)

One of the more powerful (and complex) features of Ninject is its contextual binding system. We mentioned earlier that you can register more than one binding for a type. Up until this point, we’ve only been talking about default bindings — bindings that are used unconditionally, in any context. There’s another kind of binding that’s available, a conditional binding.

As is suggested by its name, this sort of binding has a condition associated with it. This condition (represented by the ICondition<T> interface) examines the context in which the activation is occurring, and decides whether or not the binding should be used. Through the use of conditional bindings, you can design pretty much any sort of binding scheme you can dream up.

As you no doubt noticed, the ICondition<T> interface is generic, meaning it can be used to test things other than contexts. It’s also used to evaluate methods for interception, and for declaring selection heuristics. More on those things later. Right now, we’re only talking about examining the activation context, and the interface is really simple. Here it is:

interface ICondition<T> {
  bool Matches(T obj);
}

Conditions that test the activation context are generally created via the fluent interface, rooted in the When class in Ninject.Conditions. Since not all projects will require conditional binding, this namespace is actually stored in a separate assembly from Ninject.Core. To use it in your project you’ll need to first add a reference to it. Here’s an example of the fluent interface:

When.Context.Service.Name.StartsWith("Foo");

This condition will resolve to true when the service’s type name starts with Foo.

To define a conditional binding, the two fluent interfaces (binding and condition) work together. Here’s an example:

Bind<IWeapon>().To<Sword>();
Bind<IWeapon>().To<Shuriken>().Only(When.Context.Target.HasAttribute<RangeAttribute>());

With these two bindings defined, whenever an instance of IWeapon is requested, by default, Ninject will activate an instance of Sword. However, if the [target|Injection Target] that is being injected is decorated with a [Range] attribute, Ninject will activate an instance of Shuriken instead.

The [Range] attribute is just a simple attribute that you create yourself, and is used as a marker for Ninject:

public class RangeAttribute : Attribute {}

Then, you can create two different implementations of a warrior, like so:

public class Swordsman {
  [Inject] public IWeapon Weapon { get; set; }
}
public class Ninja {
  [Inject] public IWeapon MeleeWeapon { get; set; }
  [Inject, Range] public IWeapon RangeWeapon { get; set; }
}

If you’d rather not create your own attributes, Ninject supplies a [Tag] attribute that you can use instead:

public class Ninja {
  [Inject] public IWeapon MeleeWeapon { get; set; }
  [Inject, Tag("range")] public IWeapon RangeWeapon { get; set; }
}

Then, your bindings would instead look like this:

Bind<IWeapon>().To<Sword>();
Bind<IWeapon>().To<Shuriken>().Only(When.Context.Tag == "range");

However, since string-based identifiers can be prone to typing mistakes, it’s usually a good idea to just create the attributes yourself.

Continue reading: Conventions-Based Binding