Angular dependency resolution mechanism

Ramanathan Chockalingam
2 min readMar 7, 2021

Before diving into angular dependency resolution mechanism, let’s have an overview of angular injectors and their hierarchies.

Angular creates hierarchical injectors. These injectors are broadly classified into two types,

  • Module Injectors — Contain instances or values which are provided at the root or ngModule levels by using providers or provideIn property.
  • Element Injectors — contain instances or values which are provided at the component or directive level by using providers and viewproviders.

Injectors Hierarchy

Angular Injectors Hierarchy

Dependency Resolution mechanism

Phase 1: Traverse through element injector hierarchies, If the requested object is found it will be returned and the lifetime of the object depends on the components or directive scope.

Component B (Element Injector) — > Component A (Element Injector)

Phase 2: If the requested object is not present in element injector hierarchies then the request will fall back to the requestor then the traversing will start from requestor to module injector hierarchy. If the object is not found then the null injector will throw an error and stop traversing.

Component B (Element Injector) — > Component A (Element Injector)

Component B (Element Injector) — > Module Injectors Hierarchy

Note: Each element injector will have different levels of module injector hierarchy if in case child module injectors are created. Dependency resolutions can also be impacted by following decorators.

  1. @Host()
  2. @SkipSelf()
  3. @Self()
  4. @Optional()

Any module-level instances which are redeclared at component or directive levels will shadow the global instances.

References: Hierarchical Injectors

--

--