Dependency Injection Lifetimes
1 min readRapid overview
Dependency Injection Lifetimes
TL;DR
Angular's hierarchical injectors decide how long a service instance lives and how widely it's shared: root providers are app-wide singletons, module/feature providers are singletons per feature boundary, and component providers create a fresh instance per component. Choosing the right scope controls state sharing and isolation — component-level providers, for example, keep state from leaking between instances and make unit tests cleaner.
How it works
Common scopes
- Root providers: Singleton for the entire app.
- Module/feature providers: Singleton per feature boundary.
- Component providers: New instance per component instance.
Testing tips
- Provide mocks in TestBed for unit tests.
- Use component-level providers to isolate state.
Interview prompt
- When would you scope a service at the component level?