6
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?

Omar
  • 39,496
  • 45
  • 145
  • 213
  • related: http://stackoverflow.com/questions/14565380/disable-implicit-binding-injection-of-non-explicitly-bound-classes-in-ninject-2 – Ruben Bartelink May 16 '13 at 07:10

1 Answers1

9

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 for concrete types 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().

See this answer by @Remo Gloor for a way to turn it off in V2+.

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 Ninject.Extensions.Conventions 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.)

Community
  • 1
  • 1
Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249