Dependency Injection Containers - Cheat Sheet
There are a lot of articles out there that describe both Dependency Injection and Inversion of Control. The purpose of this one is to serve as a quick reference for the things I keep forgetting because configuring a DI container is something I do so infrequently. This is a very simple guide showing the easiest scenarios and the simplest syntax. It walks through the same 3 steps:
1. Create Container
2. Configure Container
3. Retrieve from Container
In the following DI libraries:
- Ninject
- Unity
- SimpleInjector
- StructureMap
Of course it will feature examples tenuously related to animals.
Principals
A Dependency Injection library makes dependency injection easier by doing the work of wiring up an "object graph" (collection of related objects) for your application to use. This is generally done at the entry point to an application:
- For console apps this is in the main method of
Program.cs
. - For MVC and Web API apps this is in
Startup.cs
. - For class libraries it is difficult to include dependency injection in the library itself as these have no defined entry point. One approach is to rely on the calling application to wire up the dependencies.
- For WebForms apps it is possible to setup the DI container in the
Global.asax
Application_Start method however it's a bit more complicated.
Console App Example
In this example we're going to begin building a console app which simulates an ecosystem of toads.