Skip to content

How Injection Works

nkohari edited this page Sep 13, 2010 · 1 revision

Ninject relies on reflection to analyze the types that it works with. However, since repeating calls via reflection can be very slow, Ninject can also take advantage of the lightweight code generation system first introduced in version 2.0 of the CLR. By default, the StandardKernel will create dynamic methods (via System.Reflection.Emit.DynamicMethod) that can be used to inject values into the different injection targets. These dynamic methods are then triggered via delegate calls.

For example, given our Samurai type:

class Samurai {
  private readonly IWeapon _weapon;
  [Inject]
  public Samurai(IWeapon weapon) {
    _weapon = weapon;
  }
  public void Attack(string target) {
    _weapon.Hit(target);
  }
}

Ninject will create a dynamic method that (basically) looks like this:

delegate(IWeapon weapon) {
  return new Samurai(weapon);
}

Then, whenever the StandardProvider associated with the Samurai needs to create a new instance, it resolves the IWeapon argument, and then passes it to the dynamic method, which in turn passes the IWeapon to the constructor of Samurai and returns the created instance.

Ninject can also be configured to use reflection for injection. Because there is some overhead involved with creating the dynamic methods, this can actually result in faster execution in some cases — particularly when you have a large number of services, but they’re all singletons.

Continue reading: Contextual Binding