What is the Dependency Injection Container (DIC)?

If you’re coding for the web, you almost certainly have encountered frameworks that make use of the Dependency Injection Container. Incredibly useful – but what is it?

In the most simplistic way – it’s just a great big bag of stuff. That’s it. There’s nothing magical about the container, it’s simply an object that stores references to other objects. Combined with a liberal use of Interfaces, this allows for a high level of abstraction and therefore also aids in unit testing smaller code parts.

For example, if you’re injecting the entire DIC into a component, you are metaphorically handing that component a great big bag of stuff and saying “here’s what we have to work with. Ask for it by name.” The component may then access the container and all configured dependencies.

You may well now be saying “well that sounds a bit like code soup” – and you’d be right. Normally, you’d only inject the dependencies that a component requires (and not the whole bag). The major frameworks (e.g. Laravel, Symfony, Zend) feature Dependency Injection Containers and an associated service locator and dependency manager. These are no longer simply “great big bags of stuff“, but true DI systems that allow for a high level of abstraction.

For a super simple Dependency Injection Container, see Pimple (by Sensio Labs). This is a great place to get started with understanding how a system will utilise a DIC. It is super simple, and forces you to understand how things are bootstrapped and provided for your system.

For more detailed information on dependency injection, see these links:

Features image (with modifications):
Coffee Bag W” by DaveBleasdale. Licensed under CC BY 2.0