Dependency Injection
A class receives what it needs instead of building it. Know the three forms Fowler named, why constructor injection is the default, what a Service Locator costs, and where the wiring lives.
Overview
Dependency Injection (DI) means an object is handed the things it depends on, instead of creating them itself. OrderService does not write self.repo = PostgresOrders(); it takes a repository as a constructor argument, and whoever builds the service decides which one. The class becomes a description of what it needs; the choice of what to give it moves out to one place.
Martin Fowler named the technique in January 2004. The lightweight containers of the time were being described as 'inversion of control', and Fowler argued that the term was too broad: frameworks invert control by nature, so saying a container is special for that reason is like saying a car is special because it has wheels. He and his colleagues chose 'Dependency Injection' to name the specific thing these containers did, and he described three forms: constructor, setter and interface injection.
Interviewers use DI to check whether you can explain the small mechanism (pass it in), the effect on tests (pass a fake in), the choice of form (constructor by default), and the difference from a Service Locator. Strong answers also know where the wiring goes: a composition root, whether written by hand or by a framework.
The mechanism
Picture the service before and after. Before, OrderService sets self.repo = PostgresOrders() in its own constructor, so it is welded to that one class. After, the service is OrderService(repo), and it depends only on an OrderRepository interface. Both PostgresOrders and a test's FakeOrders implement that interface, and a composition root picks one and passes it in.
Four pieces make up the mechanism.
- The dependency: something the class needs, such as a repository, a clock or a mailer.
- The abstraction: an interface, or a Python protocol, that the class depends on.
- The injection: passing the concrete object in, through a constructor, a setter or an interface method.
- The composition root: the one place that builds the concrete objects and wires them together.
Interview questions
- What are the three forms of dependency injection, and which should be the default?
- How does dependency injection improve unit testability?
- What is Inversion of Control, and how does it relate to DI?
- Is Service Locator an anti-pattern? Compare it with DI.
- A class takes eight constructor parameters. What does that tell you, and what do you do?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio