Tutorial – 23 – Dependency Injection

Dependency Injection

Dependency Injection is a coding pattern in which a component takes the instances of objects it needs which is called dependencies from an external source rather than creating them itself.

In Angular, services are Singleton. It internally implements the Service Locator Pattern. This means each service register itself under one container as a single instance. Angular provides a built in Injector which acts as a container to hold the single instances of all registered services. Angular takes care of creation of Service instance and registering it to the Service container.


The DI framework in Angular consists of 4 concepts working together:

This uniquely identifies something that we want injected. A dependancy of our code.
The actual code we want injected.
This is a map between a token and a list of dependancies.
This is a function which when passed a token returns a dependancy (or a list of dependencies).
To inject the service into component, Angular provides an Injector decorator : @Injectable().


An Angular injector is responsible for creating service instances and injecting them into classes.An injector is passed a token and returns a dependency (or list of dependency).


Providers tell the injector how to create the service. Without a provider, the injector would not know that it is responsible for injecting the service nor be able to create the service.


When you register a provider with an injector, you associate that provider with a dependency injection token. The injector maintains an internal token-provider map that it references when asked for a dependency. The token is the key to the map.


Leave a Reply

Your email address will not be published. Required fields are marked *