This project is read-only.
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 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;
  public Samurai(IWeapon weapon) {
    _weapon = weapon;
  public void Attack(string target) {

Public Class Samurai
  Private ReadOnly _weapon As IWeapon

  <Inject()> _
  Public Sub New(ByVal weapon As IWeapon)
    _weapon = weapon
  End Sub
  Public Sub Attack(ByVal target As String)
  End Sub
End Class

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 Samurai's constructor 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

Last edited Oct 12, 2009 at 4:52 PM by NotMyself, version 2


No comments yet.