Dependency injection
- Lesson 10 of 32
- 10 min
- Intermediate
- 11 steps
If a class calls `new` on its database and reads the system time, you cannot test it without that database or without waiting for the right day. Dependency injection hands it those parts from the outside.
- Dependencies built inside
- 0
- Test result
- always passes
- Test duration
- 2 ms
- request
- response
- slow request
- failed request
Step 1 of 11
Problem
A class that builds its own parts
TrialService answers a simple question: has this user's free trial ended? To answer it, it looks the user up in PostgreSQL and compares the end date with the current time.
The problem is how it gets those parts: it calls new PgUserRepo() in its own code and new Date() inside the method. Whoever uses the class cannot choose anything else.
You write a test, and on your machine or on the CI server there is no database: the test fails before checking anything.
Step 2 of 11
Problem
Even with a database, the result changes every day
Say you start a PostgreSQL for the tests. Now the test runs, but it is slow (every call travels to the database) and depends on whatever data is in there.
Worse: new Date() returns the real time. A user whose trial ends on January 1 is «not expired» today and «expired» tomorrow. The same test passes one day and fails the next without anyone touching the code.
The duration on the panel, 900 ms, is an example value to compare with later.
What changed
- A test PostgreSQL
- The test runs now, but slowly and depending on the day
Step 3 of 11
Concept
The idea: receive the parts instead of building them
You change one thing: TrialService asks for what it needs in its constructor, as parameters. It no longer knows which database is behind it or where the time comes from.
The parameters are typed with two small interfaces: UserRepo, with find(id), and Clock, with now(). PgUserRepo and SystemClock implement them; in the diagram the dashed arrows with a triangle leave each class and point at its interface.
That is dependency injection: someone outside hands over the dependencies already built. The logic of isExpired does not change, it just stops using new.
What changed
- `new PgUserRepo()` and `new Date()` inside the class
- Constructor taking `UserRepo` and `Clock`
Step 4 of 11
Technique
One place wires everything: the composition root
If no class builds its dependencies, someone has to. That place is the composition root: usually main.ts or the app's startup code.
There, and only there, you call new PgUserRepo(pool) and new SystemClock() and pass them to new TrialService(...). The rest of the code receives ready-made objects.
Practical case: replacing PostgreSQL with another store means writing another class that implements UserRepo and changing one line in the root, without touching TrialService.
What changed
- `main.ts` builds and connects the parts
Step 5 of 11
Solution
The test picks its own parts
In the test you do what main.ts does, but with pretend parts: a UserRepo that keeps one user in memory and a Clock that always says «February 1, 2026».
Result: no database needed, no dependence on the day, and it always returns true. In the example the duration drops from 900 ms to 2 ms (example values).
Those parts are called test doubles (fakes or stubs). They work because TrialService only knows the interfaces.
What changed
- In-memory repository and fixed clock
- A database in unit tests
Step 6 of 11
Technique
Constructor, setter or interface
Martin Fowler named this technique in 2004. He chose «dependency injection» because «inversion of control» seemed too generic a term, and he described three ways to do it.
Constructor: the dependencies come in when the object is created. Setter: a method such as setRepo(repo) assigns them later. Interface: the class implements an interface whose method receives the dependency.
Constructor injection has a practical advantage: the object never exists half-built, and its signature tells you at a glance what it needs. That is why it is the one you will see almost everywhere.
Step 7 of 11
Technique
A container wires the root for you
With dozens of classes, writing every new by hand in the root gets tiring. A DI container does that work: you tell it which classes exist and it builds and connects them.
Practical case, NestJS: you list the providers in a module and Nest resolves each constructor parameter by its type. By default every provider is a singleton. Angular does something similar: the class asks for its dependencies with inject(), and providedIn: 'root' gives one instance for the whole app.
Note: the container is optional. Injection works just the same by passing parameters by hand, as in the previous steps.
Step 8 of 11
Trade-off
The alternative that hides the parts: Service Locator
Fowler compared injection with another approach, the Service Locator: a global registry the class asks for its parts, with something like Locator.get("repo").
It also lets you swap parts in tests, but the class now depends on the locator, and its constructor no longer says what it needs. To find out, you have to read all the code.
In the diagram the arrow turns around: TrialService goes out to fetch instead of receiving.
Step 9 of 11
Trade-off
When not to inject
Not everything is a dependency. A pure function like add(a, b) or a value object like an Email has nothing to swap in a test: build them with new without guilt.
Inject what talks to the outside world or what you want to swap: database, network, clock, files, randomness.
And if a constructor asks for six or seven things, injection is not the problem: the class does too much. Split it instead of hiding the list in a container.
Step 10 of 11
Concept
Dependency injection is not dependency inversion
The names look alike, but they are not the same. Dependency inversion (the D in SOLID) is about which way dependencies point: towards abstractions such as UserRepo, not towards details such as PostgreSQL.
Injection is a technique to deliver dependencies. You can inject a concrete class without inverting anything, as in the NestJS example.
Together they work best: in the diagram every implementation, real or fake, points at the interfaces, and TrialService only knows the interfaces.
Step 11 of 11
Summary
Summary
A class receives its dependencies instead of building them with new.
The composition root is the only place that builds and connects the parts.
Tests pass doubles: no database, no real clock, fast and stable.
The container is optional; the Service Locator hides what the class needs.
Do not inject pure functions or value objects, and a huge constructor asks you to split the class.
← → step · R replay · Space pause
You will learn
- Why building dependencies inside a class makes testing hard (covered)
- Constructor injection and the composition root (covered)
- Tests with doubles: no database, no real clock (covered)
- Containers like NestJS and Angular, and the Service Locator (covered)
- When not to inject, and how it differs from dependency inversion (covered)