Angular · Lesson 3

Dependency injection

How Angular creates and shares objects. `inject()` and the injection context, providers (`useClass`, `useValue`, `useFactory`, `useExisting`), `providedIn: 'root'`, environment and element injectors, `InjectionToken`, multi providers, resolution modifiers, and overriding providers in tests.

10 min read

In short

  • inject() in a field or constructor, never later
  • providedIn: 'root': one lazy, tree-shakable instance
  • useClass, useValue, useFactory, useExisting
  • Lookup: element injectors up the tree, then route, then root
  • Component providers give each instance its own copy

Angular creates your services for you, hands them to whoever asks, and decides how long they live. That's dependency injection (DI), and it's behind most day-to-day questions on an Angular team: "is this store shared or per component?", "why are there two instances?", "how do I configure this library?", "how do I give this test a fake API?". This lesson builds an accurate picture of injectors, so those questions have obvious answers.

If you've used ASP.NET Core, the ideas will feel familiar: a container, registrations, lifetimes. There's a comparison table at the end. The exercises build an injector in plain TypeScript, step by step: provider recipes, the lookup path, a hierarchy, the injection context, multi providers, element injectors and a mini TestBed.

inject() and the injection context

import { HttpClient } from '@angular/common/http';
import { Injectable, InjectionToken, inject } from '@angular/core';
import { Observable } from 'rxjs';

export interface AppConfig {
  apiUrl: string;
  pageSize: number;
}
export const APP_CONFIG = new InjectionToken<AppConfig>('APP_CONFIG');

export interface Order {
  id: string;
  total: number;
}

@Injectable({ providedIn: 'root' })
export class OrderService {
  private readonly http = inject(HttpClient);
  private readonly config = inject(APP_CONFIG);     // typed AppConfig, from the token's type parameter

  list(page: number): Observable<Order[]> {
    return this.http.get<Order[]>(`${this.config.apiUrl}/orders`, { params: { page, size: this.config.pageSize } });
  }
}

inject(token) asks the current injector for an instance. It only works inside an injection context: while Angular is creating something. That means:

  • a constructor or a field initializer of a class Angular creates (component, directive, pipe, service),
  • a provider's useFactory function, or an InjectionToken's factory,
  • a functional guard, resolver or interceptor,
  • code wrapped in runInInjectionContext(injector, () => ...).

Anywhere else (a method called later, a setTimeout callback, code after an await) it throws NG0203. Grab what you need in a field, then use the field later.

Older code injects through constructor parameters: constructor(private http: HttpClient) {}. It's the same mechanism. inject() is preferred now because it works in plain functions, which makes small reusable helpers possible:

import { inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { ActivatedRoute } from '@angular/router';
import { map } from 'rxjs';

/** Call from a field initializer: readonly orderId = injectRouteParam('id'); */
export function injectRouteParam(name: string) {
  return toSignal(inject(ActivatedRoute).paramMap.pipe(map((params) => params.get(name))), { initialValue: null });
}

Providers: the recipe for a token

A provider tells an injector what to create for a token:

import { ApplicationConfig, ErrorHandler, inject } from '@angular/core';
import { HttpClient, provideHttpClient } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(),
    OrderService,                                                        // shorthand for { provide: OrderService, useClass: OrderService }
    { provide: ErrorHandler, useClass: AppErrorHandler },                // ask for ErrorHandler, get an AppErrorHandler
    { provide: APP_CONFIG, useValue: { apiUrl: '/api', pageSize: 20 } }, // an existing value
    { provide: OrderApi, useFactory: () => new OrderApi(inject(HttpClient), inject(APP_CONFIG).apiUrl) },
    { provide: CartReader, useExisting: CartStore },                     // an alias: the SAME instance as CartStore
  ],
};
RecipeCreatesTypical use
useClass: Xnew X() (its own inject() calls get its dependencies)swap an implementation
useValue: vnothing, returns vconfig objects, constants, test fakes
useFactory: () => ...whatever the function returns (it can call inject())logic at creation time
useExisting: Othernothing, returns the instance for Otherexpose one instance under a second token

useClass: CartStore under a second token creates a second CartStore. useExisting reuses the one you have. Mixing them up is a classic "my two components don't see the same state" bug. Exercise 1 builds these recipes.

Abstract classes make good tokens. An interface doesn't exist at runtime, so it can't be a token. An abstract class does, and it's also a type:

▶ Try
interface Logger {
  log(message: string): void;
}
abstract class KeyValueStore {
  abstract get(key: string): string | null;
}
console.log(typeof KeyValueStore);      // 'function': a real value, usable as a token
// console.log(typeof Logger);          // compile error: 'Logger' only refers to a type

So { provide: KeyValueStore, useClass: LocalStorageStore } and inject(KeyValueStore) work, typed. For non-class values (config, a function, a Window), use an InjectionToken<T>.

providedIn: 'root'

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

@Injectable({ providedIn: 'root' })
export class CartStore {}

export const WINDOW = new InjectionToken<Window>('WINDOW', { providedIn: 'root', factory: () => window });

providedIn: 'root' registers the service in the root injector, lazily: it's created the first time someone injects it, and it's a single instance for the whole app. If nothing injects it, the bundler drops it (it's "tree-shakable"), which listing it in providers would prevent. Most services should look like this. An InjectionToken with a factory works the same way, and gives the token a default.

The injector tree

There are two hierarchies:

Environment injectors                     Element injectors (components and directives with providers)
  NullInjector  -> throws NG0201            <app-root>
  platform                                    <app-checkout>        providers: [CheckoutStore]
  root          <- providedIn: 'root',          <app-address-form>  inject(CheckoutStore): the checkout's instance
                   bootstrapApplication            <app-field>     inject(CartStore): not in any element injector,
                   providers                                       so it's looked up in the environment injectors
  route         <- providers on a route

When something asks for a token, Angular:

  1. starts at the requesting component's (or directive's) element injector and walks up the component tree;
  2. if no element injector has a provider, goes back to that element's environment injector (a route's injector, then root, then platform);
  3. if nothing provides it, the NullInjector at the top throws NG0201 (No provider found for `X`. in recent versions, NullInjectorError: No provider for X! in older ones).

Where you provide something decides how many instances exist and how long they live:

  • providedIn: 'root' (or app providers): one instance for the app, lives forever.
  • A route's providers: one instance per route injector, created when that route is first used. Good for a feature's services that the rest of the app doesn't need.
  • A component's providers: a new instance per component instance, shared with everything inside it (children and projected content), and destroyed with the component (its ngOnDestroy runs). Good for state that belongs to one widget: a wizard's store, a form's state, a table's selection.
  • viewProviders is like providers, but hidden from projected content.
import { Component, Injectable, inject, signal } from '@angular/core';

@Injectable()   // no providedIn: only available where a providers array lists it
export class WizardStore {
  readonly step = signal(1);
}

@Component({
  selector: 'app-wizard',
  providers: [WizardStore],     // each <app-wizard> gets its own store, shared with its children
  template: `<app-wizard-steps /><app-wizard-nav />`,
})
export class Wizard {
  readonly store = inject(WizardStore);
}

Exercises 2, 3 and 6 build this lookup.

Resolution modifiers

inject() takes options that change where the lookup starts and stops:

OptionMeaningTypical use
optional: truereturn null instead of throwingan optional plugin or parent
self: trueonly look in the current element's own injector"this directive must be configured right here"
skipSelf: truestart at the parenta nested menu finding its parent menu
host: truestop at the host component's injectordirectives that talk to their host component
import { Component, inject } from '@angular/core';

@Component({ selector: 'app-menu', template: '<ng-content />' })
export class Menu {
  // A nested <app-menu> finds the menu it's inside. Without skipSelf it would find itself.
  readonly parentMenu = inject(Menu, { skipSelf: true, optional: true });   // Menu | null
}

With self or host, the environment injectors aren't consulted at all, so inject(CartStore, { self: true }) fails for a root service. Older code writes these as constructor parameter decorators: @Optional(), @Self(), @SkipSelf(), @Host().

Multi providers

Normally the last provider for a token wins. With multi: true, every provider adds to an array:

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

export interface SearchSource {
  name: string;
  search(query: string): Promise<string[]>;
}
export const SEARCH_SOURCES = new InjectionToken<SearchSource[]>('SEARCH_SOURCES');

export const providers = [
  { provide: SEARCH_SOURCES, useClass: OrderSearch, multi: true },
  { provide: SEARCH_SOURCES, useClass: CustomerSearch, multi: true },
  { provide: SEARCH_SOURCES, useExisting: ProductCatalog, multi: true },
];

// somewhere: inject(SEARCH_SOURCES) is [OrderSearch, CustomerSearch, the ProductCatalog instance], in that order

This is how Angular and libraries offer extension points: class-based HTTP_INTERCEPTORS, NG_VALIDATORS and NG_VALUE_ACCESSOR for forms, and the initializers behind provideAppInitializer. Mixing multi and non-multi providers for one token is an error, and a child injector's multi providers form a new list (they don't extend the parent's). Exercise 5 builds this.

Libraries wrap their providers in functions such as provideHttpClient(withInterceptors([authInterceptor])) or provideRouter(routes). Your own code can do the same with makeEnvironmentProviders([...]).

Testing with overridden providers

DI is what makes Angular code testable: a test registers fakes for the things it doesn't want to run for real.

import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';

describe('OrderService', () => {
  it('builds the URL from the config', () => {
    const calls: unknown[][] = [];
    const http = { get: (...args: unknown[]) => (calls.push(args), of([])) };   // a hand-written fake, works with any test runner
    TestBed.configureTestingModule({
      providers: [
        { provide: HttpClient, useValue: http },
        { provide: APP_CONFIG, useValue: { apiUrl: '/test-api', pageSize: 5 } },
      ],
    });

    const service = TestBed.inject(OrderService);   // providedIn: 'root', created by TestBed with the fakes
    service.list(2).subscribe();

    expect(calls).toEqual([['/test-api/orders', { params: { page: 2, size: 5 } }]]);
  });
});
  • TestBed.inject(X) creates X in the test's root injector, so a providedIn: 'root' service gets the fake dependencies you registered, even though you never listed the service itself.
  • TestBed.overrideProvider(token, { useValue }) replaces a provider wherever it's registered, including inside components (TestBed.overrideComponent(X, { set: { providers: [...] } }) replaces a component's own providers).
  • Every test gets a fresh injector, so singletons don't leak state between tests.
  • TestBed.runInInjectionContext(() => ...) runs code that calls inject(), such as a functional guard.
  • For HTTP, prefer provideHttpClient() + provideHttpClientTesting() and HttpTestingController over faking HttpClient by hand. The Testing topic covers it.

Exercise 7 builds a small TestBed.

Common mistakes

  • NG0201 / NullInjectorError: No provider for X: @Injectable() without providedIn, a missing provideHttpClient(), or a service that's only provided in a lazy route and injected from outside it.
  • Two instances when you wanted one: a root service listed again in a component's providers (that component gets its own copy), or useClass where you meant useExisting.
  • NG0203: inject() called in a method, a callback or after an await. Move it to a field.
  • NG0200 circular dependency: A injects B, which injects A. Usually a sign that one of them does too much. Extract the shared part into a third service.
  • An interface as a token: it doesn't exist at runtime. Use an abstract class or an InjectionToken.
  • A component-level store that "resets": it's created per component instance and destroyed with it. If it should survive navigation, provide it higher up (route or root).

Compared with ASP.NET Core

ASP.NET CoreAngular
services.AddSingleton<IClock, SystemClock>(){ provide: Clock, useClass: SystemClock } in app providers, or providedIn: 'root'
AddScoped (per HTTP request)a component's or route's providers (per component instance or route injector)
AddTransient (new every time)no direct equivalent: an injector caches what it creates. Use a factory function that you call.
constructor injectioninject() in a field, or constructor parameters
IOptions<T>an InjectionToken<T> with useValue
IEnumerable<IHandler> from several registrationsmulti providers
WebApplicationFactory + ConfigureTestServicesTestBed.configureTestingModule / overrideProvider

The exercises

  1. Provider recipes: InjectionToken and the four ways to create a value for a token.
  2. The resolution path: which injector answers a request, with optional, self and skipSelf.
  3. A hierarchical injector: singletons per injector, parents, token defaults, and why root services can't see child providers.
  4. inject() and the injection context: inject, runInInjectionContext, NG0203 and circular dependencies.
  5. Multi providers: plug-in lists, useExisting in a list, and child injectors that start a new list.
  6. Element and environment injectors: two hierarchies, component-scoped services and their destruction.
  7. A mini TestBed: configure, override and reset providers the way Angular tests do.

Practise this lesson

In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.

Open in the app