-
Notifications
You must be signed in to change notification settings - Fork 530
Dependency Injection With Ninject
Rather than spending time doing the “busy work” of creating and connecting your objects (and reworking the boilerplate whenever you change interdependencies between your components), you just get Ninject to figure it out for you.
When asked to instantiate an object, Ninject will look at the type’s available public constructors and picks the one with the most parameters it knows how to resolve — or the parameterless one if there aren’t any suitable ones (there’s an attribute that can be influence it’s selection – see Constructor injection for the nitty gritty).
What this means is that in the vast majority of cases you need to do little if anything to the service classes you want to resolve and have dependencies injected into in order for Ninject to be able to instantiate your objects; you normally don’t change your classes or have any need to reference Ninject classes, attributes or namespaces.
The most common thing you need to do is when the parameter being injected is specified as an interface – in that case we need to let Ninject know which concrete type to use to satisfy the interface. So if we have a service class as follows:-
class Samurai {
readonly IWeapon _weapon;
public Samurai(IWeapon weapon) {
_weapon = weapon;
}
public void Attack(string target) {
_weapon.Hit(target);
}
}
and we want to grab one like this:-
IKernel kernel = new StandardKernel();
var samurai = kernel.Get<Samurai>();
In the above case, Ninject will select the single constructor defined as the one to use. Next, it tries to resolve a value for each of the constructor’s arguments. But wait a second… IWeapon
is an interface. You can’t create an instance of an interface itself, so how does Ninject know what implementation of IWeapon
to inject?
This is accomplished through type bindings. A type binding (or just a binding) is a mapping between a service type (generally an interface or abstract class), and an implementation type to be used to satisfy such a service requirement (or a way in which to decide which one). Bindings are typically expressed via Ninject’s fluent interface. For example, to arm our Samurai
with a Sword
, we could declare the following binding:
Bind<IWeapon>().To<Sword>();
Or, if you prefer, there’s a version without generics, which can be useful for automating:
Bind(typeof(IWeapon)).To(typeof(Sword));
This binding means that whenever Ninject encounters a dependency on IWeapon
, it will resolve an instance of Sword
and inject it. This dependency resolution process is a recursive one; that is, if Sword
has any dependencies of its own, they will also be resolved before the constructor of Samurai
is called. (Also, if the dependencies of Sword
have dependencies as well, they will be resolved in turn, and so on.) In this way, Ninject can wire up an entire graph of objects for you, with minimal work on your end. You just need to set up the path, and Ninject will follow it.
The concept of type bindings is common in dependency injection containers / frameworks. However, some existing frameworks rely on XML mapping files to set up the bindings between types. Through its fluent interface, Ninject allows you to take advantage of the features of your language (like type-safety) and your IDE (like IntelliSense and code completion).
TDD and interface-based programming styles often mean you’re generally most commonly depending on interfaces. However, if the type you’re resolving is a concrete type (like Samurai
above), Ninject will automatically create a default association via a mechanism called implicit self binding. It’s as if there’s a registration like this:
Bind<Samurai>().To<Samurai>();
for every concrete type you ever try to resolve. Bear in mind that only concrete types can be self-bound; abstract types and interfaces won’t work (though there are a variety of Ninject extensions available that e.g., allow one to plug in Convention over Configuration based policies). Or… as with most things in Ninject, you can plug in your own strategy if you have specific requirements (but that customizability isn’t in your face until you need it).
Implicit self-bindings are generated in the default Object Scope (we’ll discuss that shortly). If necessary, you can override that by adding a binding of your own of the form:
Bind<Samurai>().ToSelf().// TODO add your rule overrides at the end, e.g. .InSingletonScope();
You can also have multiple bindings for a given service type, controlled by conditions that examine the context in which the instance is being resolved. This is the contextual binding system mentioned earlier, and is the key to unlocking the full power of Ninject. Don’t worry, it’s discussed in excruciating detail later. :-)
In some cases, you want your service to get a list of n related dependencies rather than just one. This is accomplished by performing 0..n type bindings and then having your service type take a parameter of type T[]
, List<T>
or Enumerable<T>
Continue reading: Injection Patterns
Licensed under Apache 2 License
Contents
- Home
- Why Use Ninject
- Getting Started
- Dependency Injection By Hand
- Dependency Injection With Ninject
- Injection Patterns
- Multi Injection
- Object Scopes
- Modules and the Kernel
- Providers, Factory Methods and the Activation Context
- The Activation Process
- How Injection Works
- Contextual Binding
- Conventions-Based Binding