Skip to content

How Injection Works

BThomann edited this page Oct 23, 2018 · 6 revisions

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
{
    readonly IWeapon weapon;
    
    [Inject]
    public Samurai(IWeapon weapon)
    {
        this.weapon = weapon;
    }
  
    public void Attack(string target) 
    {
        this.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

More details: See expression compilation