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
?
Step 1: We are creating an instance of Class StandardKernel. Step 2: Then we will load the Kernel. Step 3: Get the instance of the specific service that we want to inject. Step 4: Then inject the dependency.
Ninject is a lightweight dependency injection framework for . NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner.
Types of Dependency Injection The injector class injects dependencies broadly in three ways: through a constructor, through a property, or through a method. Constructor Injection: In the constructor injection, the injector supplies the service (dependency) through the client class constructor.
interface injection: the dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency.
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
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With