Sub topic 13
Injection Context Rules and runInInjectionContext
This chapter assumes you already know how to call inject() in a component, how providers and factory providers work, and how element injectors differ from environment injectors. Signals and effect() show up in a few examples. You do not need to know them in depth.
Earlier chapters called inject() from field initializers and factories without asking why that works. This chapter explains the rule behind it. It lists the places where inject() is allowed and the places where it throws. It also shows how to run code inside an injection context on purpose when the code would otherwise fall outside one.
What an injection context is
An injection context is a stretch of synchronous execution during which Angular has set a "current injector." inject() takes no injector argument. It reads this current injector and asks it to resolve the token.
Angular sets the current injector just before it runs code that it owns. Examples are a class constructor it is instantiating, or a factory function it is calling. Angular restores the previous value as soon as that code returns. Any inject() call made during that window, however deep in the call stack, finds the injector. Any call made outside the window finds nothing and throws.
Two consequences follow from this model:
- Call depth does not matter. A helper function called from a constructor can call
inject(), because the constructor is still on the stack. - Time does matter. A callback that runs later, after a
setTimeout, a click, a resolved promise, or anawait, runs after Angular has restored the previous injector. By then the context is gone.
Where inject() is allowed
| Call site | In context? | Notes |
|---|---|---|
| Field initializer of a class Angular instantiates | Yes | The most common form |
| Constructor body | Yes | Includes helpers called synchronously from it |
| `useFactory` function | Yes | The factory runs while the injector resolves the token |
| Functional guards, resolvers, `HttpInterceptorFn` | Yes | Router and `HttpClient` run them in an injection context |
| `runInInjectionContext(injector, fn)` callback | Yes | Only during the synchronous part of `fn` |
| `TestBed.runInInjectionContext(fn)` | Yes | Uses the test's root injector |
| `ngOnInit`, `ngOnChanges`, other lifecycle hooks | No | They run after construction |
| Template event handlers and component methods | No | They run in response to events |
| Callbacks from `setTimeout`, `subscribe`, `.then` | No | They run later |
| Code after an `await` | No | It resumes in a later microtask |
A class you create yourself with new is never in an injection context, even if it carries @Injectable. Angular only sets the current injector for instances it creates.
The NG0203 error
Calling inject() outside a context produces this runtime error:
NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`.The most common cause is moving an inject() call into a lifecycle hook:
import { Component, OnInit, inject } from '@angular/core';
import { CartService } from './cart.service';
@Component({
selector: 'app-broken',
standalone: true,
template: `{{ count }}`
})
export class BrokenComponent implements OnInit {
count = 0;
ngOnInit(): void {
// Throws NG0203: ngOnInit runs after construction has finished.
const cart = inject(CartService);
this.count = cart.count();
}
}To fix it, resolve the dependency while the component is being constructed, then use it later:
import { Component, OnInit, inject } from '@angular/core';
import { CartService } from './cart.service';
@Component({
selector: 'app-fixed',
standalone: true,
template: `{{ count }}`
})
export class FixedComponent implements OnInit {
private readonly cart = inject(CartService);
count = 0;
ngOnInit(): void {
this.count = this.cart.count();
}
}Use this pattern by default. Inject everything at construction time and keep references in fields.
Functional guards, resolvers, and the await trap
The router calls functional guards and resolvers inside an injection context. That is why they can use inject() without being classes:
import { Injectable, inject, signal } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
@Injectable({ providedIn: 'root' })
export class AuthService {
readonly isLoggedIn = signal(false);
}
export const authGuard: CanActivateFn = () => {
const auth = inject(AuthService);
const router = inject(Router);
return auth.isLoggedIn() ? true : router.parseUrl('/login');
};The context still covers only the synchronous part of the function. An async guard or resolver loses the context at its first await:
import { inject } from '@angular/core';
import { ResolveFn, Router } from '@angular/router';
import { AuthService } from './auth.guard';
async function loadProfileName(): Promise<string> {
return 'Ada';
}
export const profileResolver: ResolveFn<string> = async () => {
// Resolve every dependency before the first await.
const router = inject(Router);
const auth = inject(AuthService);
const name = await loadProfileName();
// Calling inject() here would throw NG0203.
if (!auth.isLoggedIn()) {
router.navigateByUrl('/login');
}
return name;
};Writing reusable inject helpers
You can wrap inject() calls in plain functions. These functions are often named injectX and return a ready-to-use value. They only work when the caller is in an injection context. assertInInjectionContext makes that requirement explicit and gives a clearer error that names your function:
import { Signal, assertInInjectionContext, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { ActivatedRoute } from '@angular/router';
import { map } from 'rxjs';
export function injectRouteParam(name: string): Signal<string | null> {
assertInInjectionContext(injectRouteParam);
const route = inject(ActivatedRoute);
return toSignal(route.paramMap.pipe(map(params => params.get(name))), {
initialValue: null
});
}A component uses it as a field initializer:
// Inside a routed component class:
// protected readonly productId = injectRouteParam('id');The same rule applies to several Angular APIs that call inject() internally. toSignal(), effect(), takeUntilDestroyed() with no argument, and afterNextRender() all look up DestroyRef or Injector from the current context. Calling them in a method or a hook triggers NG0203, or a related error that names the API.
runInInjectionContext
Sometimes you really need injection-context code to run later. For example, you might want to start an effect only after the user clicks a button. runInInjectionContext(injector, fn) sets the given injector as current, calls fn synchronously, and restores the previous injector afterward.
To use it, capture an injector at construction time:
import { Component, Injector, effect, inject, runInInjectionContext } from '@angular/core';
import { CartService } from './cart.service';
@Component({
selector: 'app-cart-logger',
standalone: true,
template: `<button (click)="startLogging()">Start logging</button>`
})
export class CartLoggerComponent {
private readonly injector = inject(Injector);
private readonly cart = inject(CartService);
startLogging(): void {
runInInjectionContext(this.injector, () => {
effect(() => console.log('Cart count:', this.cart.count()));
});
}
}When the API you are calling accepts an injector option, pass the injector to it directly. That route is shorter and easier to read:
// Equivalent, inside startLogging():
// effect(() => console.log('Cart count:', this.cart.count()), { injector: this.injector });
// toSignal(source$, { injector: this.injector });Use runInInjectionContext when the code you call has no such option. Your own injectX helpers and third-party helpers usually fall into this group.
Which injector to pass
The injector you pass decides both what can be resolved and how long the result lives.
| Injector passed | Sees component-level providers? | Cleanup tied to |
|---|---|---|
| `inject(Injector)` in a component | Yes, the element injector chain | The component's `DestroyRef` |
| `inject(EnvironmentInjector)` | No, environment providers only | The environment injector, usually app lifetime |
If you pass EnvironmentInjector from a component, an effect created inside it is not destroyed when the component is destroyed. That is a memory leak, and it keeps logging after the view is gone. Services provided in the component's providers array are also invisible, so resolving one of them throws NullInjectorError. Inside components, pass inject(Injector) unless you deliberately want app-lifetime behavior.
Testing code that needs a context
Unit tests for injectX helpers, functional guards, or factory functions need an injection context too. TestBed.runInInjectionContext provides one backed by the test module's injector, so overrides you register in configureTestingModule apply:
import { inject, signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { CartService } from './cart.service';
function injectCartCount(): number {
return inject(CartService).count();
}
describe('injectCartCount', () => {
it('reads the count from the provided CartService', () => {
TestBed.configureTestingModule({
providers: [{ provide: CartService, useValue: { count: signal(5) } }]
});
const count = TestBed.runInInjectionContext(() => injectCartCount());
expect(count).toBe(5);
});
});The Testing chapter covers TestBed itself. This chapter only needs the point that tests have the same context rules as application code.
Quick decision guide
- Can you move the
inject()call to a field initializer or the constructor? Do that. - Is the code a guard, resolver, interceptor, or factory? It already has a context. Keep
inject()calls before anyawait. - Does the API take an
injectoroption? Captureinject(Injector)early and pass it in. - None of the above? Capture an injector early and wrap the call in
runInInjectionContext.
Exercise
A component's ngAfterViewInit calls toSignal(this.data$). The app throws NG0203. Give two different fixes and say which one you would choose if the signal is needed for the component's whole lifetime.
Show answer
Fix one: move the call to a field initializer, as in readonly data = toSignal(this.data$), where data$ is declared above it. Fix two: capture private readonly injector = inject(Injector) and call toSignal(this.data$, { injector: this.injector }) in ngAfterViewInit. Wrapping the call in runInInjectionContext(this.injector, ...) also works. If the signal is needed for the whole lifetime, choose the field initializer. It is simpler and needs no captured injector.
Exercise
An async functional resolver calls inject(HttpClient) at the top, awaits a config load, and then calls inject(Router). Which call fails, and why does the first one succeed?
Show answer
The inject(Router) call fails with NG0203. The router invokes the resolver inside an injection context, but that context only lasts for the resolver's synchronous execution. The first inject runs before the await, while the current injector is still set. The code after the await resumes in a later microtask, after Angular has restored the previous injector.
Exercise
Inside a component that lists FormDraftService in its providers, a developer captures inject(EnvironmentInjector) and later calls runInInjectionContext(envInjector, () => inject(FormDraftService)). What happens, and what should they capture instead?
Show answer
The call throws NullInjectorError. The environment injector cannot see providers registered on the component's element injector. They should capture inject(Injector). That gives them the component's element injector, which resolves FormDraftService and ties cleanup to the component's DestroyRef.