Learning about injectors and the singleton design pattern

Injectors are elements that Angular uses to actually instantiate, retrieve, and inject dependencies where they are needed. Injectors instantiate dependencies once and store the created instances in a DI container. Each time a dependency is needed, the injector first checks whether it already has an instance of it in its container. If it does, then it returns that instance instead of creating a new one.

By creating a single instance of each injectable element, injectors apply the singleton design pattern. Singleton is a pattern that you should definitely be aware of.

If we simplify this, we can consider these containers as simple maps storing token-instance pairs. Each pair is composed of some token (for example, a unique name for a dependency) and an instance of the corresponding dependency. With the help of these containers, injectors improve application performance.

To complete the picture, providers are objects that describe how to get or create a given dependency. When you define injectable elements in your application, you also need to register a provider with an injector so that this injector can use it to instantiate the corresponding dependency. Most of the time for services, the provider is the service class itself, with the constructor acting as a factory (which it is, after all).

Thanks to all of the preceding, when Angular instantiates a component for us, it can identify its dependencies (by analyzing the constructor parameters) and ask an injector for an instance of each of those dependencies. If the injector does not already have an instance for a given dependency in its container, it will use the registered provider to create one and cache it, before returning it to Angular. Finally, once Angular has all the required dependencies, it can instantiate the component.

Injectors also maintain a map containing token-provider pairs, making a link between an injection token (https://angular.io/guide/glossary#di-token) and a provider.

Let's continue.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.106.100