Dependency Injection (DI)

Dependency Injection (DI) in Angular: In a well-run hospital, an operating room does not sterilize its own instruments.

The Analogy: A Hospital Central Sterile Supply Department

In a well-run hospital, an operating room does not sterilize its own instruments. When a surgeon needs a certified laparoscopy set, the OR requests it by name from the Central Sterile Supply Department (CSSD), and a stamped, tracked, ready-to-use tray arrives. The OR never sources, cleans, or certifies the tools itself; it declares what kind of set it needs and trusts the department to supply a conforming one. Angular's dependency injection works the same way: a class declares in its constructor what services it needs, by type, and the injector supplies a ready, configured instance. The class asks for a collaborator; it does not build one.

Central supply is a single hospital-wide department, and by default everyone who asks for a given set gets served from that same department. This is providedIn: 'root': the injector creates one shared instance the first time it is requested and hands that identical instance to every class that asks afterward. A stateless service - one that just formats data or calls an API - is perfect as this kind of singleton, exactly as one sterilization standard serves the whole building.

Some floors, though, run their own satellite sterilizer for speed. When a room on that floor asks for a set, the request is answered by the floor's local unit rather than travelling all the way to central supply; only if the floor has no unit does the request bubble up to the hospital department. Angular injectors form the same hierarchy: a component that lists a service in its own providers gets a fresh instance scoped to that component and its children, and an unsatisfied request climbs from component to parent to root until some injector can supply it.

The failure mode is the surgeon who grabs an instrument off a random shelf and cleans it at the sink - calling new SomeService() by hand instead of asking the injector. It may work once, but the instrument is now off the books: nobody can swap in a different certified supplier, nobody can substitute a safe practice dummy during a drill, and nobody can audit what was actually used. In code this is the hard-constructed dependency that cannot be mocked in a test or reconfigured for a different environment, because the class welded itself to one concrete implementation.


Syntax or Core Structure

A service is an ordinary class marked with the @Injectable decorator, which tells Angular the class can participate in DI. Setting providedIn: 'root' registers it with the root injector as an application-wide singleton. A component then declares the dependency as a constructor parameter typed with the service class; Angular reads that type and supplies the instance - the component writes no new.

import { Injectable, Component } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class DataService {
  getData(): string[] {
    return ['A', 'B', 'C'];
  }
}

@Component({
  selector: 'app-list',
  template: `<p>{{ items.join(',') }}</p>`
})
export class ListComponent {
  items: string[];
  constructor(private data: DataService) {
    this.items = this.data.getData();
  }
}

Two components that both inject DataService receive the very same object, because the root injector caches the instance after first creating it. The next model captures that injector directly so the singleton behavior is visible.

The injector is essentially a registry of factories with a cache. This minimal model captures the essential rule - create once, then reuse:

class Injector {
  constructor() { this.providers = new Map(); this.cache = new Map(); }
  provide(token, factory) { this.providers.set(token, factory); }
  get(token) {
    if (!this.cache.has(token)) {
      this.cache.set(token, this.providers.get(token)());
    }
    return this.cache.get(token);
  }
}

let created = 0;
class DataService {
  constructor() { created++; }
  getData() { return ['A', 'B', 'C']; }
}

const root = new Injector();
root.provide('DataService', () => new DataService());

const a = root.get('DataService');
const b = root.get('DataService');
console.log('data: ' + a.getData().join(','));
console.log('same instance: ' + (a === b));
console.log('instances created: ' + created);

Output:

data: A,B,C
same instance: true
instances created: 1

Technical Depth: Injector Scope and Provider Recipes

The root singleton is only the default. Real apps lean on the injector hierarchy to scope some services more narrowly, and on provider recipes to control exactly what an injector hands back.

The injector hierarchy

Every component has its own injector, chained to its parent's, up to the root. When a class asks for a token, the nearest injector that has a provider wins; otherwise the request bubbles upward. A service listed in a component's providers therefore yields a fresh, component-scoped instance, while an unlisted one resolves to the shared root instance. This model shows both paths - a floor with no local unit shares the root instance, an OR with its own provider gets a separate one:

class HierInjector {
  constructor(parent = null) {
    this.parent = parent;
    this.providers = new Map();
    this.cache = new Map();
  }
  provide(token, factory) { this.providers.set(token, factory); }
  get(token) {
    if (this.providers.has(token)) {
      if (!this.cache.has(token)) {
        this.cache.set(token, this.providers.get(token)());
      }
      return this.cache.get(token);
    }
    if (this.parent) return this.parent.get(token);
    throw new Error('No provider for ' + token);
  }
}

let n = 0;
class Sterilizer { constructor() { n++; this.tag = 'S' + n; } }

const root = new HierInjector();
root.provide('Sterilizer', () => new Sterilizer());
const floor = new HierInjector(root);              // no own provider
const or1 = new HierInjector(floor);
or1.provide('Sterilizer', () => new Sterilizer()); // own provider
console.log('floor uses: ' + floor.get('Sterilizer').tag);
console.log('root again: ' + root.get('Sterilizer').tag);
console.log('or1 uses: ' + or1.get('Sterilizer').tag);

Output:

floor uses: S1
root again: S1
or1 uses: S2

Provider recipes

providedIn and providers decide the scope; a provider recipe decides what the injector actually returns for a token. The recipe lets you swap a class for a value, a factory, or an alias without changing a single consumer.

Provider recipeWhat the injector returnsSterile-supply analogy
useClassA new instance of a classA standard certified set
useValueA fixed, ready-made valueA pre-packed disposable kit
useFactoryWhatever a function computesA set assembled to order
useExistingAn alias to another tokenA second label on one cart

Injection tokens for non-class values

Classes make natural tokens, but interfaces and primitives do not survive compilation, so you cannot inject "a string" or "a config object" by type alone. Angular's InjectionToken creates a unique, typed key for exactly these cases - an API base URL, a feature flag, a configuration record - which a provider then binds with useValue or useFactory. This keeps even plain values flowing through the same tracked, swappable injector rather than hard-coded across the app.

Constructor injection versus inject()

The classic way to receive a dependency is a constructor parameter, and it remains the most common. Angular 14 and later also offer a standalone inject() function that resolves a token from the current injector without a constructor, which is handy in field initializers, base-class helpers, and functional route guards:

import { inject } from '@angular/core';

@Component({ selector: 'app-report', template: '{{ rows.length }} rows' })
export class ReportComponent {
  private data = inject(DataService);
  rows = this.data.getData();
}

Both forms hit the same injector and obey the same hierarchy and provider rules; inject() simply removes the constructor boilerplate and composes better with functional APIs. The choice is stylistic, not semantic - the tracked, swappable supply chain is identical either way.


Real World Example: Swapping a Logger for Tests

DI's biggest practical payoff is substitution. Because OrderService receives its logger through the constructor instead of constructing one, the same class runs against a real console logger in production and a silent buffer logger in a test - no code inside OrderService changes.

class ConsoleLogger {
  log(message) { return '[console] ' + message; }
}

class BufferLogger {
  constructor() { this.lines = []; }
  log(message) { this.lines.push(message); return '[buffer] ' + message; }
}

class OrderService {
  constructor(logger) { this.logger = logger; this.total = 0; }
  add(price) {
    this.total += price;
    return this.logger.log('added ' + price + ', total ' + this.total);
  }
}

// production wiring
const prod = new OrderService(new ConsoleLogger());
console.log(prod.add(10));
console.log(prod.add(5));

// test wiring: inject a buffer, assert on captured lines
const buffer = new BufferLogger();
const underTest = new OrderService(buffer);
underTest.add(10);
underTest.add(5);
console.log('captured: ' + buffer.lines.join('; '));

Output:

[console] added 10, total 10
[console] added 5, total 15
captured: added 10, total 10; added 5, total 15

The program isolates one idea: OrderService never names a concrete logger. Production hands it a ConsoleLogger whose lines you can see, while the test hands it a BufferLogger and then asserts on buffer.lines. The business logic - accumulate a total, log each addition - is identical in both runs, and the totals 10 then 15 prove the service behaved the same regardless of which logger it received.

In real Angular you would define the seam as an abstract Logger class or an InjectionToken, provide ConsoleLogger in the application and a fake in TestBed. The component that injects Logger is written once and never learns which implementation it got, exactly as an OR requests a certified set without knowing which sterilizer produced it.

This is why externalizing construction pays off: testability, environment-specific configuration, and safe substitution all follow from the single decision not to call new inside the class. Nothing has to reach in and monkey-patch a global, because the dependency was always a seam the injector controls.

The genuine design flaw hides in OrderService's state. It keeps a mutable total, so if a developer reflexively marks it providedIn: 'root' - the most common default - every component that injects it shares one running total, and one screen's cart silently contaminates another's. A stateful service must be scoped deliberately: list it in a component's providers so each consumer gets its own instance, or move the per-user total into a keyed store, and reserve root for stateless helpers. Choosing a scope is a design decision, not a default to accept blindly.


Common Mistakes

  1. Calling new on a dependency. Hand-constructing a service inside a class welds it to one implementation, so it cannot be mocked in a test or reconfigured per environment. Declare it as a constructor parameter and let the injector supply it.
  2. Marking a stateful service providedIn: 'root'. A root singleton shares one instance across the whole app, so mutable state such as a running total or a draft form leaks between unrelated consumers. Scope stateful services to a component.
  3. Re-providing a meant-to-be-singleton service in many components. Listing a service in several components' providers gives each its own instance, quietly breaking shared state you expected to be global.
  4. Trying to inject by interface. TypeScript interfaces do not exist at runtime, so constructor(x: MyInterface) has nothing to look up. Use a class or an InjectionToken as the token.
  5. Creating circular dependencies. If service A injects B and B injects A, the injector cannot resolve either. Break the cycle by extracting shared logic, and reach for forwardRef only as a last resort.
  6. Forgetting @Injectable() on a service that itself injects. Without the decorator Angular lacks the metadata to resolve the service's own constructor dependencies.
  7. Defaulting everything to root. Not every service should be an application-wide singleton; feature- or component-scoped services keep lifetimes and memory tied to where they are actually used.
  8. Depending on concrete classes instead of abstractions. Injecting a specific implementation makes substitution awkward; depend on an abstract class or token so any conforming provider can be swapped in.
  9. Doing heavy work in a constructor. Constructors run at injection time, so HTTP calls or expensive setup there are hard to sequence and test. Keep constructors to field assignment and move real work into ngOnInit or a lazy initializer.

Best Practices

  • Depend on abstractions - an abstract class or an InjectionToken - rather than concrete classes, so any conforming implementation can be provided or mocked.
  • Keep root services stateless; when a service must hold mutable per-view state, scope it to the component with its own providers.
  • Prefer providedIn on the @Injectable decorator over listing services in an NgModule, since tree-shakable providers drop unused services from the bundle.
  • Use InjectionToken for configuration values and primitives, binding them through useValue or useFactory so even plain values travel through the injector.
  • Keep constructors cheap - assign injected fields and nothing more - and move HTTP calls or setup into ngOnInit or a lazy initializer.
  • Supply test doubles through TestBed provider overrides instead of monkey-patching globals, which keeps tests aligned with real wiring.
  • Choose each service's scope deliberately from its lifetime and state, rather than reflexively reaching for root.
  • Break potential circular dependencies early by extracting the shared concern into a third, lower-level service both can inject.

Practice Exercises

  1. Build a tiny injector. Implement a class with provide(token, factory) and get(token) that caches instances, then register one service, resolve it twice, and prove with an instance counter that only one object was created.
  2. Demonstrate and fix a state leak. Model a stateful counter service shared as a root singleton across two consumers and show the value bleeding between them; then give each consumer its own instance and confirm the totals stay independent.
  3. Swap an implementation behind a token. Define a Logger seam (an abstract class or InjectionToken), provide a console implementation and a buffering one, and write a consumer that behaves identically against either.
  4. Invert a hard-coded dependency. Take a class that calls new on a collaborator, refactor it to receive that collaborator through its constructor, and write a small test that passes in a fake to assert on the interaction.