Dependency Injection Strategies
Desliza para mostrar el menú
Before exploring advanced dependency injection (DI) patterns, you need to recall how Angular's dependency injection (DI) system and hierarchical injectors operate. Angular uses a powerful DI framework to manage service creation and injection. At its core, the DI system allows you to declare dependencies in constructors, and Angular resolves these dependencies at runtime.
The injector hierarchy is key:
- The root injector is created at application bootstrap and provides services registered with the
providedIn: 'root'option or in the root module; - Each module, component, and directive can also have its own injector, forming a tree structure;
- When Angular resolves a dependency, it starts at the requesting component's injector and traverses up the hierarchy until it finds a provider or throws an error if none is found.
This system enables flexible service scoping and overrides, supporting both singleton and localized service instances.
app/services/root-logger.service.ts
app/logger.module.ts
app/services/module-logger.service.ts
app/components/component-logger/component-logger.component.ts
app/services/component-logger.service.ts
When you provide services at different levels—root, module, or component—you are leveraging Angular's hierarchical injectors to control service scope. Services provided at the root are singletons throughout the app. Module-level providers create a new instance for consumers within that module and its children, while component-level providers ensure a unique instance per component instance. This flexibility is crucial for advanced scenarios.
Multi-provider tokens and factory providers further expand your DI options:
- Multi-provider tokens let you associate multiple providers with a single injection token, useful for plugin systems or registering multiple strategies;
- Factory providers allow you to customize how a service is created, even injecting dependencies dynamically based on runtime conditions.
Both patterns interact with the DI hierarchy: multi-providers aggregate values up the injector tree, while factory providers can be scoped at any injector level, giving you fine-grained control over instantiation and configuration.
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla