views:

49

answers:

2
public class MyController : Controller
{
   private MyClass _class;

   public MyController(MyClass class)
   {
       this._class = class;
   }
}

public class MyClass
{
      // stuff
}

My Ninject is hooked up to inject classes that implement IController (Controller class does so). But, I did not bind MyClass to anything, yet Ninject is still injecting MyClass into MyController.

I guess my question is, why does it inject something that I didn't bind to anything? Does Ninject run off an find the class with the signature MyClass? I assume this behavior would be different if my constructor required a MyBaseClass and I have two classes in my assembly that inherit from MyBaseClass?

A: 

Because MyClass is a concrete class, Ninject knows how to create a new instance of MyClass and binding is not needed.

Steven
+1  A: 

In Ninject V1, ImplicitSelfBinding was a top-level config setting (which defaulted to true IIRC).

In V2, the implicit self binding behavior you observe is more deeply wired in (though there are ways of switching it off -- like most bits of Ninject, it's very granular and minimal). In V2, the default behavior is that self-bindings are always generated if no other binding is present. The only time you typically do a Bind<Concrete>().ToSelf() is to customise the binding, e.g., to do a .InSingletonScope().

Go do a grep in the source right now for ImplicitSelfBinding this instant - it's far easier to read than people rabbiting on though!

Also dont forget to have a look at the scannning extensions and tests on ninject.org for arranging implicit Bind()ing of I*X* to *X*

(As Steven alluded to, Ninject would not self bind if you changed your MyClass class to be abstract.)

Ruben Bartelink