A test that passes on exactly one day
A city library charges 50 cents for every day a loan is overdue. The code is a LateFeeService with one method, feeFor(loanId): load the loan, compare its due date with the current time, multiply. Inside, it does two innocent-looking things. Its constructor builds a PostgresLoanRepository, and feeFor calls Date.now() whenever it needs the time.
Then someone writes the obvious test: a loan due on 1 March, checked on 4 March, owes $1.50. The test has no way, short of faking the clock for the whole process, to say "today is 4 March", because the service reads the real clock, so the expected fee is right on one day and wrong on every other. It also cannot run without a Postgres server holding exactly that loan. Nothing in the service is buggy. It has decided, inside itself, which database and which clock it will use, and nothing outside it can change that decision.
Ask for them in the constructor
The fix is to move both decisions out. LateFeeService stops creating its collaborators and lists them as constructor parameters instead: a LoanRepository, an interface with the one method the service needs, findLoan(id), and a Clock, with now(). Whoever creates the service hands those in, and that one move is Dependency Injection. The service still needs a repository and a clock; it has simply stopped choosing them. Whoever builds it, a test, main or a container, now decides which implementation it gets, usually through the constructor and sometimes through a setter.
The test now builds the service with an in-memory repository holding one loan and a clock that always answers 4 March, and asserts $1.50. It runs in milliseconds, on any day, with no database. Production builds the same class with the Postgres repository and a clock that reads the system time. LateFeeService is identical in both; only what it was given differs.
The composition root decides which repository the service receives; the service only ever names the interface.
Look at what the service depends on now: two small interfaces, not a Postgres class. Making the high-level policy depend on an abstraction instead of on a low-level detail is the Dependency Inversion Principle, and it has its own section in SOLID design principles. The two names are easy to mix up. The principle is a rule about which way dependencies point; injection is a mechanism for supplying them. You can inject a concrete class, too: you still control how it is built, but in a language that checks types by name, such as Java or C#, you can swap it only for that class or a subclass of it.
Then who calls new?
The construction has not disappeared. It has moved to the edge of the program, usually main or the web app's startup code, where one block builds the real objects and hands them to each other: create the Postgres repository and the system clock, pass both to LateFeeService, pass the service to the HTTP handler that serves the fees page. That place is called the composition root. It is the one part of the program that knows every concrete class, which is why the rest of the program does not have to.
In a small application, writing that wiring by hand is fine and easy to read. Once the object graph runs to dozens of services, it gets long and repetitive, and that is the job of a DI container, also called an IoC container: you register which implementation goes with which interface, and the container builds each object and its dependencies for you, typically by reading constructor parameters. Spring, the container built into ASP.NET Core and Angular's injector are well-known examples. A container automates the composition root; it is not what makes code injectable. A class that takes its dependencies through its constructor is already using Dependency Injection, with no framework at all.
LoanRepository above is such a port.Constructor, setter or method
Constructor injection is the default for a reason. A dependency the object cannot work without belongs in the constructor: the object is complete the moment it exists, and its signature lists everything it needs. Setter injection, a property or setter called after construction, suits a dependency that is optional or must be replaceable later, at the price of a window in which the object exists without it; a LateFeeService whose clock arrives through a setter breaks on any call made before that setter runs. Method injection passes the dependency as an argument to the one method that needs it, which fits a collaborator that changes on every call, such as a formatter for the current reader's locale. For the case where the injected thing is an interchangeable algorithm, see Strategy; for an optional dependency that would otherwise be null, a stand-in that does nothing, see Null Object.
Four ways to undo it
- A fallback
new. Having the consumer new-up its own dependency as a fallback when the container doesn't provide one, as inthis.loans = loans ?? new PostgresLoanRepository(), silently reintroduces the concrete coupling DI exists to remove. The class still imports Postgres, and a test that forgets one argument quietly talks to a real database. - Fetching from a global registry. If the service calls
Registry.get("loans")inside its methods, it no longer creates the dependency but still fetches it itself, and the constructor stops telling you what the class needs. This is the Service Locator approach. Every test has to prepare the registry first, and a missing registration shows up only when that line runs. - A constructor with eleven parameters. Injection makes a class's dependencies visible, and sometimes what becomes visible is a class doing too many jobs. Then split the class; hiding the parameters in a container or a settings object only hides the problem.
- A long-lived object holding a short-lived one. If a container keeps
LateFeeServiceas one instance for the whole application and injects a per-request database session into it, every later request reuses the first request's session. A dependency should live at least as long as the object holding it.
Swap the implementation without touching the consumer
The Dependency Injection challenge asks for exactly this wiring. Build the library's version, or a service of your own with two implementations of one dependency: a Component node for the consumer, a Port / Interface node for what it depends on, a Service or Component node for each implementation, and a Dependency Injection node for the container. Then check three things. The consumer's only arrow goes to the interface. Every arrow that hands over an implementation starts at the container. And replacing the production implementation with the test one changes an edge at the container, never at the consumer.