Patterncore
Dependency injection
Also called DI, constructor injection, inversion of control.
An object receives its collaborators from outside, usually as constructor parameters, instead of creating them or looking them up. One place in the program chooses them.
- Family
- architectural
- Intent
- Separate the configuration of the services that an object uses from the use of those services, so the object depends on roles and the program chooses the implementations in one place.
- Also called
- Inversion of Control (for the containers)
Intent
Separate the configuration of the services that an object uses from the use of those services.1 The object declares the roles it needs, such as a clock or a mailer, and receives objects for those roles from outside. One place in the program, the composition root, chooses the implementations and connects them.
Dependency injection is a small technique with a large name. In most code it is a constructor parameter. This page explains why that parameter matters, what the alternatives are, and when a container that does the wiring is worth its cost.
Problem
A service sends reminders for invoices that are overdue. A first version finds its collaborators by itself:
import datetime
import smtplib
class ReminderService:
def remind(self, invoice):
late = (datetime.date.today() - invoice.due).days
if late > 0:
smtplib.SMTP("mail.example.com").send_message(...)
The code works in production. It has three problems that all come from one decision: the service chooses its own collaborators.
- A test cannot run it. The test cannot set the date, and every run sends real mail.
- The program cannot configure it. A second deployment with another mail server needs a change to the class.
- A reader cannot see what it needs. The dependencies are inside the method bodies.
Fowler's article starts with the same shape: a MovieLister class that creates its own MovieFinder and so depends on both the interface and the implementation.1 The forces are these. The class must work with any implementation of a role. The program must choose the implementations in one place. And the class should state what it needs, so that a reader, a compiler or a test can see it.
Solution
Give the collaborators to the object. The class declares parameters with the types of the roles, and stores what it receives. It never names an implementation.
composition root (main)
clock = FixedClock(40) chooses the implementations
mailer = ConsoleMailer()
service = ReminderService(clock, mailer)
|
v
ReminderService ----uses----> Clock (role: today())
----uses----> Mailer (role: send(to, text))
^ ^
FixedClock | | ConsoleMailer, RecordingMailer
Fowler describes three forms.1
- Constructor injection. The constructor takes the collaborators. The object is complete when it exists.
- Setter injection. A setter method or a property takes each collaborator after construction.
- Interface injection. The class implements an interface whose method receives the collaborator.
Fowler's own advice is to start with constructor injection. A constructor with parameters makes clear what a valid object is, and it lets the fields be immutable. He also lists the limits of constructors: many parameters, parameters that are known only by their position, and several ways to build a valid object. In those cases he accepts setters.1 The Spring documentation gives the same advice: constructors for mandatory dependencies and setters for optional ones. It adds that a constructor with many arguments is a sign that the class has too many responsibilities.3
The example files implement ReminderService with a Clock and a Mailer in each language. main is the composition root, and a test wires the same class to a RecordingMailer. In Python, the roles are typing.Protocol classes, so an implementation matches by its methods and needs no base class.5
The alternative: a service locator
A service locator is a registry that the class asks for its collaborators. It also separates configuration from use. The class depends on the locator, and the locator holds the implementations.1 The difference shows when the configuration is incomplete:
This code raises KeyError, on purpose.
from dataclasses import dataclass
class Locator:
_services = {}
@classmethod
def register(cls, name, service):
cls._services[name] = service
@classmethod
def get(cls, name):
return cls._services[name]
@dataclass
class Invoice:
number: int
customer: str
due: int
class FixedClock:
def today(self):
return 40
class ReminderService:
def __init__(self): # the constructor says nothing about what it needs
pass
def remind(self, invoice):
late = Locator.get("clock").today() - invoice.due
if late > 0:
Locator.get("mailer").send(invoice.customer, f"invoice {invoice.number} is {late} days overdue")
Locator.register("clock", FixedClock()) # the mailer was never registered
service = ReminderService()
service.remind(Invoice(18, "bo@example.com", 45))
print("not late: no mail, so no error yet")
service.remind(Invoice(17, "ana@example.com", 31))
The missing mailer is found only when an invoice is late, which can be weeks after a deployment. With constructor injection, the service cannot be built without a mailer. Fowler names this difference: with injection, the constructor shows the dependencies, and with a locator, a reader must search the source for calls to the locator.1
Fowler did not reject the locator. He wrote that for the classes of one application the two are close, and that injection is the better choice for a class that many applications use.1 Seemann later argued that a service locator is an anti-pattern, because it hides the dependencies of a class and turns a mistake that a compiler could catch into an error at run time.2 The block above shows that run-time error.
A plain argument is often enough
Most of the benefit comes from one rule: the code that makes a decision does not fetch its own inputs. When a dependency is a value, pass the value. When it is one operation, pass a function. A class with an injected clock is often a function that wants today's date:
from dataclasses import dataclass
@dataclass(frozen=True)
class Invoice:
number: int
customer: str
due: int
def reminder(invoice: Invoice, today: int) -> str | None:
"""Decides. Reads nothing from outside, sends nothing."""
late = today - invoice.due
return f"invoice {invoice.number} is {late} days overdue" if late > 0 else None
def send_reminders(invoices, today, send=print):
"""Acts. The caller passes the date and the way to send."""
for invoice in invoices:
text = reminder(invoice, today)
if text:
send(f"to {invoice.customer}: {text}")
invoices = [Invoice(17, "ana@example.com", 31), Invoice(18, "bo@example.com", 45)]
send_reminders(invoices, today=40)
# The tests need no doubles for the decision, and a list for the action.
assert reminder(invoices[1], today=45) is None
assert reminder(invoices[1], today=50) == "invoice 18 is 5 days overdue"
sent = []
send_reminders(invoices, today=50, send=sent.append)
print(sent)
to ana@example.com: invoice 17 is 9 days overdue
['to ana@example.com: invoice 17 is 19 days overdue', 'to bo@example.com: invoice 18 is 5 days overdue']
reminder is a pure function. A test calls it with a day and checks the result. send_reminders takes the sending operation as a parameter, so a test passes sent.append. This is dependency injection with no interface, no class and no container. In a language with first-class functions, a role with one operation is a function type. See Higher-order function and Closure.
Example
Each example file builds ReminderService with a clock and a mailer, sends the reminders for two invoices in main, and runs the same class against a recording mailer. Each language describes the roles in its own way:
| Language | Role | Wiring |
|---|---|---|
| Python | typing.Protocol |
constructor parameters |
| JavaScript | any object with the methods | one options object |
| TypeScript | interface, checked by shape |
constructor parameters |
| Java | interface; a lambda for a role with one method |
constructor, final fields |
| C# | interface |
primary constructor |
| Go | small interface, satisfied implicitly | constructor function |
| Rust | trait, as a generic parameter |
new with generic types |
| C++ | abstract class | references in the constructor |
| C | function pointer and context pointer | a struct literal |
from dataclasses import dataclass
from typing import Protocol
class Clock(Protocol):
def today(self) -> int: ...
class Mailer(Protocol):
def send(self, to: str, text: str) -> None: ...
@dataclass(frozen=True)
class Invoice:
number: int
customer: str
due: int # day number
class ReminderService:
"""Depends on a clock and a mailer. It does not know which ones."""
def __init__(self, clock: Clock, mailer: Mailer) -> None:
self._clock = clock
self._mailer = mailer
def remind(self, invoice: Invoice) -> bool:
late = self._clock.today() - invoice.due
if late <= 0:
return False
self._mailer.send(invoice.customer, f"invoice {invoice.number} is {late} days overdue")
return True
# Implementations of the two roles.
class FixedClock:
def __init__(self, day: int) -> None:
self.day = day
def today(self) -> int:
return self.day
class ConsoleMailer:
def send(self, to: str, text: str) -> None:
print(f"to {to}: {text}")
class RecordingMailer:
def __init__(self) -> None:
self.sent: list[str] = []
def send(self, to: str, text: str) -> None:
self.sent.append(f"to {to}: {text}")
def main() -> None:
# The composition root: the one place that chooses the implementations.
service = ReminderService(FixedClock(40), ConsoleMailer())
invoices = [Invoice(17, "ana@example.com", 31), Invoice(18, "bo@example.com", 45)]
sent = sum(service.remind(i) for i in invoices)
print(f"reminders sent: {sent}")
# A test wires the same class to other implementations.
recorder = RecordingMailer()
ReminderService(FixedClock(50), recorder).remind(invoices[1])
print(f"recorded: {recorder.sent[0]}")
main()
to ana@example.com: invoice 17 is 9 days overdue
reminders sent: 1
recorded: to bo@example.com: invoice 18 is 5 days overdue
- Verdict: idiom. Python has no construct for injection. A constructor that takes its collaborators as parameters is the whole technique.
ClockandMaileraretyping.Protocolclasses, soFixedClockandConsoleMailermatch them by their methods, with no base class. A type checker verifies the match. At run time, any object with the right methods works.mainis the composition root. It is the only function that names the concrete classes.RecordingMaileris a test double. The service runs in the test with no mail server and no real date.
#include <iostream>
#include <string>
#include <vector>
struct Clock {
virtual ~Clock() = default;
virtual int today() const = 0;
};
struct Mailer {
virtual ~Mailer() = default;
virtual void send(const std::string& to, const std::string& text) = 0;
};
struct Invoice {
int number;
std::string customer;
int due; // day number
};
// The service holds references. Whoever builds it owns the collaborators.
class ReminderService {
public:
ReminderService(const Clock& clock, Mailer& mailer) : clock_(clock), mailer_(mailer) {}
bool remind(const Invoice& invoice) {
int late = clock_.today() - invoice.due;
if (late <= 0) return false;
mailer_.send(invoice.customer,
"invoice " + std::to_string(invoice.number) + " is " +
std::to_string(late) + " days overdue");
return true;
}
private:
const Clock& clock_;
Mailer& mailer_;
};
class FixedClock : public Clock {
public:
explicit FixedClock(int day) : day_(day) {}
int today() const override { return day_; }
private:
int day_;
};
class ConsoleMailer : public Mailer {
public:
void send(const std::string& to, const std::string& text) override {
std::cout << "to " << to << ": " << text << "\n";
}
};
class RecordingMailer : public Mailer {
public:
std::vector<std::string> sent;
void send(const std::string& to, const std::string& text) override {
sent.push_back("to " + to + ": " + text);
}
};
int main() {
// The composition root owns every object, and they live until main returns.
FixedClock clock(40);
ConsoleMailer mailer;
ReminderService service(clock, mailer);
std::vector<Invoice> invoices{{17, "ana@example.com", 31}, {18, "bo@example.com", 45}};
int sent = 0;
for (const auto& invoice : invoices) sent += service.remind(invoice);
std::cout << "reminders sent: " << sent << "\n";
// A test wires the same class to a recording double.
FixedClock later(50);
RecordingMailer recorder;
ReminderService(later, recorder).remind(invoices[1]);
std::cout << "recorded: " << recorder.sent[0] << "\n";
}
to ana@example.com: invoice 17 is 9 days overdue
reminders sent: 1
recorded: to bo@example.com: invoice 18 is 5 days overdue
- Verdict: idiom. Abstract classes with pure virtual functions describe the roles, and the constructor takes references to them.
- The service holds references, so it does not own its collaborators. They must outlive the service. Here
mainowns them all, so a reader can check that rule in one function. A service that must own a collaborator takes astd::unique_ptr, and one that shares it takes astd::shared_ptr. - A template parameter instead of a virtual base gives static injection, as in the Rust example: no virtual calls, and one copy of the class for each set of types.
import java.util.ArrayList;
import java.util.List;
public class Main {
interface Clock { int today(); }
interface Mailer { void send(String to, String text); }
record Invoice(int number, String customer, int due) {}
static final class ReminderService {
private final Clock clock;
private final Mailer mailer;
// Constructor injection: the object is complete when it exists.
ReminderService(Clock clock, Mailer mailer) {
this.clock = clock;
this.mailer = mailer;
}
boolean remind(Invoice invoice) {
int late = clock.today() - invoice.due();
if (late <= 0) return false;
mailer.send(invoice.customer(), "invoice " + invoice.number() + " is " + late + " days overdue");
return true;
}
}
record FixedClock(int day) implements Clock {
public int today() { return day; }
}
static final class ConsoleMailer implements Mailer {
public void send(String to, String text) { System.out.println("to " + to + ": " + text); }
}
static final class RecordingMailer implements Mailer {
final List<String> sent = new ArrayList<>();
public void send(String to, String text) { sent.add("to " + to + ": " + text); }
}
public static void main(String[] args) {
// The composition root.
var service = new ReminderService(new FixedClock(40), new ConsoleMailer());
var invoices = List.of(new Invoice(17, "ana@example.com", 31), new Invoice(18, "bo@example.com", 45));
long sent = invoices.stream().filter(service::remind).count();
System.out.println("reminders sent: " + sent);
// A test wires the same class to a recording double.
var recorder = new RecordingMailer();
new ReminderService(new FixedClock(50), recorder).remind(invoices.get(1));
System.out.println("recorded: " + recorder.sent.get(0));
// Clock has one method, so a lambda can be the clock.
Clock lateClock = () -> 60;
new ReminderService(lateClock, recorder).remind(invoices.get(0));
System.out.println("recorded: " + recorder.sent.get(1));
}
}
to ana@example.com: invoice 17 is 9 days overdue
reminders sent: 1
recorded: to bo@example.com: invoice 18 is 5 days overdue
recorded: to ana@example.com: invoice 17 is 29 days overdue
- Verdict: idiom. Interfaces describe the roles, and
finalfields that the constructor sets hold the collaborators. Fowler gives this as a reason to prefer constructor injection: the fields can be immutable, and the object is valid as soon as it exists. Clockhas one abstract method, so it is a functional interface, and the lambda() -> 60implements it. A role with one operation needs no class.- Containers such as Spring create and wire these objects from annotations or configuration. The standard library has no container, and this program does not need one.
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
/* A role is a function pointer and a context pointer. */
struct clock { int (*today)(void *ctx); void *ctx; };
struct mailer { void (*send)(void *ctx, const char *to, const char *text); void *ctx; };
struct invoice { int number; const char *customer; int due; };
struct reminder_service { struct clock clock; struct mailer mailer; };
static bool remind(const struct reminder_service *s, const struct invoice *inv) {
int late = s->clock.today(s->clock.ctx) - inv->due;
if (late <= 0) return false;
char text[80];
snprintf(text, sizeof text, "invoice %d is %d days overdue", inv->number, late);
s->mailer.send(s->mailer.ctx, inv->customer, text);
return true;
}
/* Implementations. */
static int fixed_today(void *ctx) { return *(const int *)ctx; }
static void console_send(void *ctx, const char *to, const char *text) {
(void)ctx;
printf("to %s: %s\n", to, text);
}
struct recording { char sent[4][96]; int count; };
static void recording_send(void *ctx, const char *to, const char *text) {
struct recording *r = ctx;
if (r->count < 4) snprintf(r->sent[r->count++], sizeof r->sent[0], "to %s: %s", to, text);
}
int main(void) {
/* The composition root. */
int day = 40;
struct reminder_service service = {{fixed_today, &day}, {console_send, NULL}};
const struct invoice invoices[] = {{17, "ana@example.com", 31}, {18, "bo@example.com", 45}};
int sent = 0;
for (size_t i = 0; i < 2; i++) sent += remind(&service, &invoices[i]);
printf("reminders sent: %d\n", sent);
/* A test wires the same function to a recording double. */
int later = 50;
struct recording recorder = {0};
struct reminder_service test = {{fixed_today, &later}, {recording_send, &recorder}};
remind(&test, &invoices[1]);
printf("recorded: %s\n", recorder.sent[0]);
return 0;
}
to ana@example.com: invoice 17 is 9 days overdue
reminders sent: 1
recorded: to bo@example.com: invoice 18 is 5 days overdue
- Verdict: idiom. A struct with a function pointer and a
void *context plays the role of an interface. The caller fills it, soremindnever names an implementation. - The context pointer carries the state of each implementation, such as the day of the fixed clock or the list of the recorder. The compiler cannot check that a context has the type that the function expects.
- Link-time substitution is the other C technique: the test links a different object file that defines the same functions. It needs no pointers, but it fixes one implementation for each executable.
// The composition root.
var service = new ReminderService(new FixedClock(40), new ConsoleMailer());
Invoice[] invoices = [new(17, "ana@example.com", 31), new(18, "bo@example.com", 45)];
var sent = invoices.Count(service.Remind);
Console.WriteLine($"reminders sent: {sent}");
// A test wires the same class to a recording double.
var recorder = new RecordingMailer();
new ReminderService(new FixedClock(50), recorder).Remind(invoices[1]);
Console.WriteLine($"recorded: {recorder.Sent[0]}");
interface IClock { int Today(); }
interface IMailer { void Send(string to, string text); }
record Invoice(int Number, string Customer, int Due);
// A primary constructor takes the collaborators.
sealed class ReminderService(IClock clock, IMailer mailer)
{
public bool Remind(Invoice invoice)
{
var late = clock.Today() - invoice.Due;
if (late <= 0) return false;
mailer.Send(invoice.Customer, $"invoice {invoice.Number} is {late} days overdue");
return true;
}
}
sealed class FixedClock(int day) : IClock
{
public int Today() => day;
}
sealed class ConsoleMailer : IMailer
{
public void Send(string to, string text) => Console.WriteLine($"to {to}: {text}");
}
sealed class RecordingMailer : IMailer
{
public List<string> Sent { get; } = [];
public void Send(string to, string text) => Sent.Add($"to {to}: {text}");
}
to ana@example.com: invoice 17 is 9 days overdue
reminders sent: 1
recorded: to bo@example.com: invoice 18 is 5 days overdue
- Verdict: idiom. Interfaces describe the roles, and a primary constructor receives the collaborators. The parameters
clockandmailerare in scope in every member of the class. - The .NET libraries for hosted applications include a container in the package Microsoft.Extensions.DependencyInjection. It calls this same constructor. The package is not part of the base library, so this program wires the objects by hand.
TimeProviderin the base library is a clock abstraction that a class can receive in its constructor, for the same reason asIClockhere.
// The service receives its collaborators. It never creates them.
class ReminderService {
#clock;
#mailer;
constructor({ clock, mailer }) {
this.#clock = clock;
this.#mailer = mailer;
}
remind(invoice) {
const late = this.#clock.today() - invoice.due;
if (late <= 0) return false;
this.#mailer.send(invoice.customer, `invoice ${invoice.number} is ${late} days overdue`);
return true;
}
}
// Implementations are plain objects. Each one only needs the right methods.
const fixedClock = (day) => ({ today: () => day });
const consoleMailer = { send: (to, text) => console.log(`to ${to}: ${text}`) };
function recordingMailer() {
const sent = [];
return { sent, send: (to, text) => sent.push(`to ${to}: ${text}`) };
}
// The composition root.
const service = new ReminderService({ clock: fixedClock(40), mailer: consoleMailer });
const invoices = [
{ number: 17, customer: "ana@example.com", due: 31 },
{ number: 18, customer: "bo@example.com", due: 45 },
];
const sent = invoices.filter((i) => service.remind(i)).length;
console.log(`reminders sent: ${sent}`);
// A test wires the same class to a recording double.
const recorder = recordingMailer();
new ReminderService({ clock: fixedClock(50), mailer: recorder }).remind(invoices[1]);
console.log(`recorded: ${recorder.sent[0]}`);
to ana@example.com: invoice 17 is 9 days overdue
reminders sent: 1
recorded: to bo@example.com: invoice 18 is 5 days overdue
- Verdict: idiom. The constructor takes one object with named properties, so the call site shows which collaborator is which and the order does not matter.
- The collaborators are object literals and closures. JavaScript checks nothing at the call: a mailer without
sendfails only whenremindcalls it. - Private fields (
#clock,#mailer) keep other code from replacing a collaborator after construction.
interface Clock {
today(): number;
}
interface Mailer {
send(to: string, text: string): void;
}
interface Invoice {
readonly number: number;
readonly customer: string;
readonly due: number;
}
class ReminderService {
readonly #clock: Clock;
readonly #mailer: Mailer;
constructor(clock: Clock, mailer: Mailer) {
this.#clock = clock;
this.#mailer = mailer;
}
remind(invoice: Invoice): boolean {
const late = this.#clock.today() - invoice.due;
if (late <= 0) return false;
this.#mailer.send(invoice.customer, `invoice ${invoice.number} is ${late} days overdue`);
return true;
}
}
class FixedClock implements Clock {
readonly #day: number;
constructor(day: number) {
this.#day = day;
}
today(): number {
return this.#day;
}
}
class ConsoleMailer implements Mailer {
send(to: string, text: string): void {
console.log(`to ${to}: ${text}`);
}
}
class RecordingMailer implements Mailer {
readonly sent: string[] = [];
send(to: string, text: string): void {
this.sent.push(`to ${to}: ${text}`);
}
}
// The composition root.
const service = new ReminderService(new FixedClock(40), new ConsoleMailer());
const invoices: Invoice[] = [
{ number: 17, customer: "ana@example.com", due: 31 },
{ number: 18, customer: "bo@example.com", due: 45 },
];
const sent = invoices.filter((i) => service.remind(i)).length;
console.log(`reminders sent: ${sent}`);
// A test double needs no class at all: an object literal has the right shape.
const recorded: string[] = [];
const recorder: Mailer = { send: (to, text) => recorded.push(`to ${to}: ${text}`) };
new ReminderService(new FixedClock(50), recorder).remind(invoices[1]);
console.log(`recorded: ${recorded[0]}`);
to ana@example.com: invoice 17 is 9 days overdue
reminders sent: 1
recorded: to bo@example.com: invoice 18 is 5 days overdue
- Verdict: idiom. Interfaces describe the roles, and the constructor parameters have those types. The compiler rejects a call with a collaborator of the wrong shape.
- TypeScript types are structural.
FixedClocknamesClockinimplements, but the object literalrecorderalso counts as aMailer, because it has asendmethod with the right type. - The interfaces exist only at compile time. A container that reads constructor parameter types at run time needs decorators and metadata from a library, which this page does not use.
package main
import "fmt"
// The consumer declares the small interfaces it needs.
type Clock interface{ Today() int }
type Mailer interface{ Send(to, text string) }
type Invoice struct {
Number int
Customer string
Due int // day number
}
type ReminderService struct {
clock Clock
mailer Mailer
}
func NewReminderService(clock Clock, mailer Mailer) *ReminderService {
return &ReminderService{clock: clock, mailer: mailer}
}
func (s *ReminderService) Remind(inv Invoice) bool {
late := s.clock.Today() - inv.Due
if late <= 0 {
return false
}
s.mailer.Send(inv.Customer, fmt.Sprintf("invoice %d is %d days overdue", inv.Number, late))
return true
}
type FixedClock int
func (c FixedClock) Today() int { return int(c) }
type ConsoleMailer struct{}
func (ConsoleMailer) Send(to, text string) { fmt.Printf("to %s: %s\n", to, text) }
type RecordingMailer struct{ Sent []string }
func (m *RecordingMailer) Send(to, text string) {
m.Sent = append(m.Sent, fmt.Sprintf("to %s: %s", to, text))
}
func main() {
// The composition root.
service := NewReminderService(FixedClock(40), ConsoleMailer{})
invoices := []Invoice{{17, "ana@example.com", 31}, {18, "bo@example.com", 45}}
sent := 0
for _, inv := range invoices {
if service.Remind(inv) {
sent++
}
}
fmt.Printf("reminders sent: %d\n", sent)
// A test wires the same type to a recording double.
recorder := &RecordingMailer{}
NewReminderService(FixedClock(50), recorder).Remind(invoices[1])
fmt.Printf("recorded: %s\n", recorder.Sent[0])
}
to ana@example.com: invoice 17 is 9 days overdue
reminders sent: 1
recorded: to bo@example.com: invoice 18 is 5 days overdue
- Verdict: idiom. A struct holds interface values, and a constructor function fills them. Go has no container in the standard library, and the usual Go program wires its objects by hand in
main. - Interfaces are satisfied implicitly.
FixedClockandRecordingMailerdo not nameClockorMailer, so the package that consumes a role can declare the interface, with only the methods it calls. FixedClockis a namedint. A role with one method does not need a struct.RecordingMailer.Sendhas a pointer receiver because it changes the slice. So*RecordingMailersatisfiesMailer, andRecordingMailerdoes not.
use std::cell::RefCell;
trait Clock {
fn today(&self) -> i32;
}
trait Mailer {
fn send(&self, to: &str, text: &str);
}
struct Invoice {
number: u32,
customer: &'static str,
due: i32,
}
// Generic over its collaborators: the compiler makes one copy for each pair of types.
struct ReminderService<C: Clock, M: Mailer> {
clock: C,
mailer: M,
}
impl<C: Clock, M: Mailer> ReminderService<C, M> {
fn new(clock: C, mailer: M) -> Self {
Self { clock, mailer }
}
fn remind(&self, invoice: &Invoice) -> bool {
let late = self.clock.today() - invoice.due;
if late <= 0 {
return false;
}
let text = format!("invoice {} is {late} days overdue", invoice.number);
self.mailer.send(invoice.customer, &text);
true
}
}
struct FixedClock(i32);
impl Clock for FixedClock {
fn today(&self) -> i32 {
self.0
}
}
struct ConsoleMailer;
impl Mailer for ConsoleMailer {
fn send(&self, to: &str, text: &str) {
println!("to {to}: {text}");
}
}
#[derive(Default)]
struct RecordingMailer {
sent: RefCell<Vec<String>>,
}
impl Mailer for &RecordingMailer {
fn send(&self, to: &str, text: &str) {
self.sent.borrow_mut().push(format!("to {to}: {text}"));
}
}
fn main() {
// The composition root.
let service = ReminderService::new(FixedClock(40), ConsoleMailer);
let invoices = [
Invoice { number: 17, customer: "ana@example.com", due: 31 },
Invoice { number: 18, customer: "bo@example.com", due: 45 },
];
let sent = invoices.iter().filter(|i| service.remind(i)).count();
println!("reminders sent: {sent}");
// The test keeps the recorder and lends it to the service.
let recorder = RecordingMailer::default();
ReminderService::new(FixedClock(50), &recorder).remind(&invoices[1]);
println!("recorded: {}", recorder.sent.borrow()[0]);
}
to ana@example.com: invoice 17 is 9 days overdue
reminders sent: 1
recorded: to bo@example.com: invoice 18 is 5 days overdue
- Verdict: idiom. Traits describe the roles. The service is generic over them, so each call to a collaborator is a static call that the compiler can inline. A
Box<dyn Mailer>field is the other choice: one service type, and the implementation chosen at run time. sendtakes&self, so the recording double keeps its list in aRefCellto change it through a shared reference.- The test lends
&recorderto the service and reads the list afterwards.impl Mailer for &RecordingMailermakes the reference itself a mailer, so the service does not take ownership of the recorder.
Consequences
Benefits.
- The class can be tested alone. A test passes doubles for the roles. No mail server, no clock, no database. See Unit testing.
- The configuration is in one place. The composition root is the only code that names the implementations. Changing the mail server changes one line.
- The dependencies are visible. The constructor lists them. A class whose constructor takes nine parameters shows its size, and that is useful information.3
- The implementations can vary. The injected role is often a Strategy pattern. A program can wrap one in a Decorator pattern or a Proxy pattern at the composition root, and the class does not change.
Liabilities.
- Indirection. A reader of the class sees
self._mailer.sendand must look at the composition root to learn which mailer runs. With a container, that information is in configuration or annotations, further from the code. - Interfaces with one implementation. A team that injects everything can end up with an interface for every class, each with one implementation and one test double. That is cost with no variation to pay for it.
- Containers add their own rules. A container creates objects with a lifetime: one for the application, one for each request, or one for each use. A service with a short lifetime that is held by one with a long lifetime lives too long. The .NET documentation says that a scoped service resolved from the root provider acts as a singleton, and the provider checks for this in development.4 Errors of this kind come from the container, not from the program's logic.
- Wiring errors at startup. With a container, a missing registration is an error when the container first builds the object. That can be at startup or at the first request. It is later than a compiler error for a constructor call written by hand.
When not to use it
Do not inject what does not vary. A class that formats a date with a fixed pattern does not need the formatter injected. Inject a dependency when there is a second implementation, or when a test needs a double because the real one is slow, has side effects, or is not deterministic: the clock, the network, the file system, random numbers.
Do not add a container to a small program. A main function that calls constructors is a composition root. It is checked by the compiler and readable in one place. Every example on this page wires by hand.
Do not use setter injection for a required dependency. An object between its constructor and its last setter call is not valid, and nothing stops code from using it in that state.13
Do not inject the container. A class that receives the container and asks it for services is a service locator with a different name, and it has the hidden dependencies of one.2
Do not inject a class to replace a value. If the code needs today's date, a parameter today is clearer than a Clock with one method, as the plain argument example shows.
Variants and related patterns
Inversion of control. Fowler wrote that "inversion of control" is too generic a term, because every framework inverts control. He used the name Dependency Injection for the specific inversion in which a container supplies the dependencies of an object.1
Service Locator. The class asks a registry for its collaborators. It separates configuration from use, but each class depends on the locator, and the dependencies are not visible in the constructor.12
Singleton. A singleton gives global access to one instance. Injection with a single instance keeps the "one instance" and drops the global access: the composition root creates one object and passes it to everyone who needs it. See Singleton pattern.
Abstract Factory and Factory Method. When a class must create objects of a role at run time, not receive one, inject a factory. See Abstract Factory pattern and Factory Method pattern.
Strategy. An injected role with one operation that varies is a strategy, chosen by the composition root instead of by the client. See Strategy pattern.
Template Method. A subclass that overrides a hook is the inheritance form of the same idea: the varying part comes from outside the base class. Injection does it by composition. See Template Method pattern.
Interfaces. Injection works because the class depends on a role, not a class. See Interfaces.
Known uses
- CPython:
socketserver.BaseServer.__init__in Lib/socketserver.py at v3.14.0 takesRequestHandlerClassas a constructor parameter. The server stores it and creates an instance of it for each request. A program injects its handler class, and the server never names one.6 - Go: the
Transportfield ofhttp.Clientin net/http/client.go at go1.23.0 takes aRoundTripper, the role that makes one HTTP request. The comment says thatDefaultTransportis used if the field is nil. Tests and proxies set the field, and the client code does not change.7
References
- Martin Fowler, Inversion of Control Containers and the Dependency Injection pattern, 23 January 2004, Components and Services; A Naive Example; Inversion of Control; Forms of Dependency Injection; Using a Service Locator; Deciding which option to use; Concluding Thoughts
- Mark Seemann, Service Locator is an Anti-Pattern, 3 February 2010, whole post
- Spring Framework reference, Dependency Injection, Constructor-based or setter-based DI?
- .NET dependency injection, Microsoft Learn, Scope validation
- The Python Standard Library, typing, Python 3.14, typing.Protocol
- CPython v3.14.0 source, Lib/socketserver.py, BaseServer.__init__, lines 203 to 208
- Go go1.23.0 source, src/net/http/client.go, type Client, field Transport, lines 57 to 61
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag DQ8MTH Edit this page History Report an error Markdown