Sub topic 2
How Dependency Injection Works
This chapter explains the model that sits under every Angular service: what an injector is, how it finds or builds the objects you ask for, and why those objects are usually shared. Later chapters cover the syntax for declaring services, the inject() function, and provider registration in detail. Here you build a mental model accurate enough to predict what Angular will do, and to read its error messages when it doesn't.
You should already know TypeScript classes and generics, how standalone components and bootstrapApplication work, and basic ES module imports. The examples use inject() and @Injectable() without explaining them fully. Treat them as "ask for a dependency" and "this class can be built by Angular" for now.
The problem DI solves
A class that needs another object has two choices. It can build that object itself, or someone else can hand it over. Building it yourself looks simple until the dependencies have dependencies of their own.
Here is a small checkout flow wired by hand, in plain TypeScript with no Angular:
class RateTable {
rateFor(region: string): number {
return region === 'EU' ? 0.2 : 0.07;
}
}
class TaxCalculator {
constructor(private readonly rates: RateTable) {}
tax(amount: number, region: string): number {
return amount * this.rates.rateFor(region);
}
}
class CheckoutService {
constructor(private readonly taxCalc: TaxCalculator) {}
total(amount: number, region: string): number {
return amount + this.taxCalc.tax(amount, region);
}
}
const checkout = new CheckoutService(new TaxCalculator(new RateTable()));
console.log(checkout.total(100, 'EU')); // 120The classes take their dependencies as constructor parameters, which is already good design. The trouble is the last lines. Whoever writes new CheckoutService(...) has to know the whole graph: that CheckoutService needs a TaxCalculator, which needs a RateTable. Each component that wants checkout must repeat this wiring, and each gets its own copy of every object. If RateTable later needs an HTTP client, every call site changes.
Dependency injection (DI) moves the wiring into one place. A consumer states what it needs. A container called an injector works out how to build it, builds its dependencies first, and hands back the result.
The vocabulary
Angular's DI system uses a handful of terms. They come up in every later chapter and in error messages, so it helps to pin them down now.
| Term | Meaning | In the checkout example |
|---|---|---|
| Dependency | An object a class needs in order to work | `TaxCalculator` is a dependency of `CheckoutService` |
| Consumer | The code asking for a dependency | `CheckoutService` |
| Token | The lookup key that identifies a dependency | The class `TaxCalculator` itself |
| Provider | A recipe that tells an injector how to create the value for a token | "call `new TaxCalculator()`" |
| Injector | The object that holds providers, creates values, and caches them | The injector built by `Injector.create` below |
The split between token and provider matters most. The token is what you ask for. The provider is how the value gets made. Usually the token is a class and the provider is "construct that class", so the two look like the same thing. They are separate, though, and later chapters swap the provider while keeping the token. That is how you replace a real service with a fake in tests, or pick an implementation at runtime.
Watching an injector work
You rarely create injectors yourself, because Angular builds them when the application bootstraps. Creating one by hand is still the clearest way to see the mechanics. The code below uses Injector.create, the same low-level API Angular builds on. Run it inside an Angular CLI project, for example by pasting it at the top of main.ts or into a spec file, so the decorators are compiled.
import { Injectable, Injector, inject } from '@angular/core';
@Injectable()
export class RateTable {
constructor() {
console.log('RateTable created');
}
rateFor(region: string): number {
return region === 'EU' ? 0.2 : 0.07;
}
}
@Injectable()
export class TaxCalculator {
private readonly rates = inject(RateTable);
constructor() {
console.log('TaxCalculator created');
}
tax(amount: number, region: string): number {
return amount * this.rates.rateFor(region);
}
}
@Injectable()
export class CheckoutService {
private readonly taxCalc = inject(TaxCalculator);
constructor() {
console.log('CheckoutService created');
}
total(amount: number, region: string): number {
return amount + this.taxCalc.tax(amount, region);
}
}
const injector = Injector.create({
providers: [RateTable, TaxCalculator, CheckoutService]
});
console.log('injector ready');
const checkout = injector.get(CheckoutService);
console.log(checkout.total(100, 'EU'));
const again = injector.get(CheckoutService);
console.log(again === checkout);The console shows:
injector ready
RateTable created
TaxCalculator created
CheckoutService created
120
trueEach line of that output tells you something about how the injector behaves.
Creation is lazy
injector ready prints first. Registering a provider creates nothing. The injector only stores the recipe and runs it the first time someone asks for the token. A service nobody requests is never constructed.
Dependencies are resolved depth-first
Asking for CheckoutService starts building it. Its field initializer calls inject(TaxCalculator), so the injector pauses and builds TaxCalculator. That class's field initializer calls inject(RateTable), so RateTable is built first. The constructors finish innermost-first: RateTable, then TaxCalculator, then CheckoutService. This is the same order as the hand-written new CheckoutService(new TaxCalculator(new RateTable())), but the injector worked it out by itself.
Instances are cached per injector
The second injector.get(CheckoutService) returns the same object, and nothing is constructed again. An injector creates at most one instance per token and reuses it for every later request. That is why services are described as singletons. They are singletons within one injector, not globally. Two injectors with a provider for the same token give you two separate instances, and later chapters use that on purpose to scope state to a component subtree.
What the injector does on each request
When code asks an injector for a token, the injector follows the same steps every time:
- Check its cache. If it already holds an instance for this token, return it.
- Look for a provider for this token in its own records.
- If it has one, run the recipe. Any
inject()calls inside the recipe start this same process again for their tokens. Cache the result and return it. - If it has no provider, pass the request to its parent injector.
- If no injector up the chain has a provider, the top of the chain throws an error.
Step 4 is where Angular's design gets interesting. A real application has many injectors arranged in a tree: one for the application as a whole and more for components that declare their own providers. A request that misses locally moves upward until something answers. The chapter on the injector hierarchy traces that walk in detail. For now, remember that "which instance do I get?" means "which is the nearest injector with a provider for this token?"
When resolution fails
Two failures account for most DI errors you will see. Both are easier to fix once you know which step of the lookup broke.
Missing provider
Remove TaxCalculator from the providers array and ask for CheckoutService again:
import { Injector } from '@angular/core';
import { CheckoutService, RateTable } from './checkout';
const broken = Injector.create({ providers: [RateTable, CheckoutService] });
try {
broken.get(CheckoutService);
} catch (err) {
console.error((err as Error).message);
}Angular throws a NullInjectorError. The message names the missing token (No provider for TaxCalculator!) and the path that led to it, such as CheckoutService -> TaxCalculator. Read the path from left to right. The last entry is the token nobody could provide, and the entries before it show who needed it. The name comes from the NullInjector at the very top of every injector chain, whose only job is to throw this error.
In a real application, the usual causes are a class missing providedIn: 'root', a provider registered on a component that isn't an ancestor of the consumer, or a module or provider function never added to bootstrapApplication.
Circular dependency
If A injects B and B injects A, step 3 never ends. Building A needs B, and building B needs the A that is still under construction. Angular detects this and throws error NG0200 (circular dependency in DI detected), listing the cycle. The fix is a design change, not a DI setting. You can extract the shared logic into a third service that both depend on, or have one side receive data through method arguments instead of holding a reference.
Why this design pays off
The injector gives you three things you would otherwise build by hand:
- Decoupling. Consumers name a token and never call
newon their dependencies, so a dependency's own dependencies can change without touching the consumers. - Sharing. Per-injector caching gives every consumer under the same injector the same instance, which is what makes a service a good place for shared state.
- Substitution. Because the token and the provider are separate, you can register a different provider for the same token. Tests, environment-specific implementations, and configuration all rely on this.
Exercises
Exercise
In the Injector.create example, suppose you add a fourth service, ReceiptService, that calls inject(CheckoutService) in a field initializer. You register it, call injector.get(CheckoutService) first, then injector.get(ReceiptService). How many times does each "created" message print, and in what order?
Show answer
Each message prints once. The first get prints RateTable created, TaxCalculator created, CheckoutService created. The second get finds no cached ReceiptService, runs its recipe, and its inject(CheckoutService) returns the cached instance, so only "ReceiptService created" prints (if it logs one). Instances are cached per injector and never rebuilt.
Exercise
An error message reads "No provider for RateTable!" with the path "CheckoutService -> TaxCalculator -> RateTable". Which class is missing a provider, and which class's code triggered the request for it?
Show answer
RateTable is missing a provider. TaxCalculator triggered the request, because it appears directly before RateTable in the path. CheckoutService only appears because it needed TaxCalculator.
Exercise
You create two injectors with Injector.create, each listing RateTable in its providers, and call get(RateTable) on both. Are the results the same object? What does this tell you about the word "singleton" in Angular?
Show answer
No, they are two different objects. Each injector keeps its own cache, so a service is a singleton only within the injector that provides it. Providing the same token in several injectors produces several instances.