Dependency Injection 5.0
Dependency injection is an important app design pattern. It’s used so widely that almost everyone just calls it DI.
Angular has its own dependency injection framework, and you really can’t build an Angular app without it.
This page covers what DI is, why it’s useful, and how to use Angular DI.
Why dependency injection?
To understand why dependency injection is so important, consider an example without it. Imagine writing the following code:
Car class creates everything it needs inside its constructor.
What’s the problem?
The problem is that the
Car class is brittle, inflexible, and hard to test.
Car needs an engine and tires. Instead of asking for them,
Car constructor instantiates its own copies from
the very specific classes
What if the
Engine class evolves and its constructor requires a parameter?
That would break the
Car class and it would stay broken until you rewrote it along the lines of
engine = new Engine(theNewParameter).
Engine constructor parameters weren’t even a consideration when you first wrote
You may not anticipate them even now.
But you’ll have to start caring because
when the definition of
Engine changes, the
Car class must change.
What if you want to put a different brand of tires on your
Car? Too bad.
You’re locked into whatever brand the
Tires class creates. That makes the
Car class inflexible.
Right now each new car gets its own engine. It can’t share an engine with other cars.
While that makes sense for an automobile engine,
surely you can think of other dependencies that should be shared, such as the onboard
wireless connection to the manufacturer’s service center. This
Car lacks the flexibility
to share services that have been created previously for other consumers.
When you write tests for
Car you’re at the mercy of its hidden dependencies.
Is it even possible to create a new
Engine in a test environment?
Engine depend upon? What does that dependency depend on?
Will a new instance of
Engine make an asynchronous call to the server?
You certainly don’t want that going on during tests.
What if the
Car should flash a warning signal when tire pressure is low?
How do you confirm that it actually does flash a warning
if you can’t swap in low-pressure tires during the test?
You have no control over the car’s hidden dependencies. When you can’t control the dependencies, a class becomes difficult to test.
How can you make
Car more robust, flexible, and testable?
See what happened? The definition of the dependencies are
now in the constructor.
Car class no longer creates an engine or tires.
It just consumes them.
This example leverages Dart’s constructor syntax for declaring parameters and initializing properties simultaneously.
Now you can create a car by passing the engine and tires to the constructor.
How cool is that?
The definition of the engine and tire dependencies are
decoupled from the
You can pass in any kind of engine or tires you like, as long as they
conform to the general API requirements of an engine or tires.
If someone extends the
Engine class, that is not
The consumer of
Car has the problem. The consumer must update the car creation code to
something like this:
The critical point is this: the
Car class did not have to change.
You’ll take care of the consumer’s problem shortly.
Car class is much easier to test now because you are in complete control
of its dependencies.
You can pass mocks to the constructor that do exactly what you want them to do
during each test:
You just learned what dependency injection is.
It’s a coding pattern in which a class receives its dependencies from external sources rather than creating them itself.
Cool! But what about that poor consumer?
Anyone who wants a
Car must now
create all three parts: the
Car class shed its problems at the consumer’s expense.
You need something that takes care of assembling these parts.
You could write a giant class to do that:
It’s not so bad now with only three creation methods. But maintaining it will be hairy as the app grows. This factory is going to become a huge spiderweb of interdependent factory methods!
Wouldn’t it be nice if you could simply list the things you want to build without having to define which dependency gets injected into what?
This is where the dependency injection framework comes into play. Imagine the framework had something called an injector. You register some classes with this injector, and it figures out how to create them.
When you need a
Car, you simply ask the injector to get it for you and you’re good to go.
Everyone wins. The
Car knows nothing about creating an
The consumer knows nothing about creating a
You don’t have a gigantic factory class to maintain.
Car and consumer simply ask for what they need and the injector delivers.
This is what a dependency injection framework is all about.
Angular dependency injection
Angular ships with its own dependency injection framework.
You’ll learn Angular dependency injection through a discussion of the sample app that accompanies this page.
Start by reviewing this simplified version of the heroes feature from the The Tour of Heroes.
HeroesComponent is the top-level heroes component.
It’s only purpose is to display the
which displays a list of hero names.
This version of the
HeroListComponent gets its heroes from
mockHeroes, an in-memory collection
defined in a separate file.
That may suffice in the early stages of development, but it’s far from ideal.
As soon as you try to test this component or get heroes from a remote server,
you’ll have to change the implementation of
replace every other use of the
Create an injectable HeroService
It’s better to hide the details concerning hero data access inside a service class, defined in its own file.
Assume for now that the
@Injectable() annotation is an essential ingredient in every Angular service definition.
The service class exposes a
that returns the same mock data as before.
Of course, this isn’t a real data service.
If the service were actually getting data from a remote server,
getHeroes() method signature would be asynchronous.
Such a hero service is presented in the
tutorial section on Heroes and HTTP.
The focus here is on service injection, so a synchronous service will suffice.
Register a service provider
A service is just a class (or a top-level function) until you register it with an Angular dependency injector.
An Angular injector is responsible for creating service instances and injecting them into classes like the
Angular creates most injectors for you as it executes the app, starting from the (optional) root injector that you supply as an argument to the runApp() function.
You must register providers with an injector before the injector can create that service.
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.
You’ll learn more about providers below. For now it is sufficient to know that they create services and must be registered with an injector.
The most common way to register a provider is with
any Angular annotation that has a
providers list argument.
The most common of these is @Component().
Here’s a revised
HeroesComponent that registers the
HeroService in its
An instance of the
HeroService is now available for injection in this
and all of its child components.
A component-provided service may have a limited lifetime. Each new instance of the component gets its own instance of the service and, when the component instance is destroyed, so is that service instance.
In this sample app, the
HeroComponent is created when the app starts
and is never destroyed so the
HeroService created for the
HeroComponent also lives for the life of the app.
Root injector providers
You can also register providers in the app’s root injector, which you pass as an argument to the runApp() function:
An instance of the
HeroService will now be available for injection across the entire app.
Use root injector provisioning for app-wide services declared external to the app package. This is why registering app specific services is discouraged.
The preferred approach is to register app services in app components.
HeroService is used within the Heroes feature set, and nowhere else,
the ideal place to register it is in
Here’s a more realistic example of a root injector, taken from the tutorial, part 5:
Inject a service
HeroListComponent should get heroes from the
The component shouldn’t create the
It should ask for the
HeroService to be injected.
You can tell Angular to inject a dependency in the component’s constructor by specifying a constructor parameter with the dependency type.
HeroListComponent constructor, asking for the
HeroService to be injected.
Of course, the
HeroListComponent should do something with the injected
Here’s the revised component, making use of the injected service, side-by-side with the previous version for comparison.
Notice that the
HeroListComponent doesn’t know where the
HeroService comes from.
You know that it comes from the parent
The only thing that matters is that the
HeroService is provided in some parent injector.
Services are singletons within the scope of an injector. There is at most one instance of a service in a given injector.
However, Angular DI is a hierarchical injection system, which means that nested injectors can create their own service instances. Angular creates nested injectors all the time.
Component child injectors
For example, when Angular creates a new instance of a component that has
it also creates a new child injector for that instance.
Component injectors are independent of each other and each of them creates its own instances of the component-provided services.
When Angular destroys one of these component instances, it also destroys the component’s injector and that injector’s service instances.
Thanks to injector inheritance, you can still inject app-wide services into these components. A component’s injector is a child of its parent component’s injector, and a descendent of its parent’s parent’s injector, and so on all the way back to the app’s root injector. Angular can inject a service provided by any injector in that lineage.
Testing the component
Earlier you saw that designing a class for dependency injection makes the class easier to test. Listing dependencies as constructor parameters may be all you need to test app parts effectively.
For example, you can create a new
HeroListComponent with a mock service that you can manipulate
Learn more in Testing.
When the service needs a service
HeroService is very simple. It doesn’t have any dependencies of its own.
What if it had a dependency? What if it reported its activities through a logging service?
You’d apply the same constructor injection pattern,
adding a constructor that takes a
Here is the revised
HeroService that injects the
Logger, side-by-side with the previous service for comparison.
The constructor asks for an injected instance of a
Logger and stores it in the private
getHeroes() method logs a message when asked to fetch heroes.
The dependent Logger service
The sample app’s
Logger service is quite simple:
A real implementation would probably use the logging package.
If the app didn’t provide this
Angular would throw an exception when it looked for a
Logger to inject
EXCEPTION: No provider for Logger! (HeroListComponent -> HeroService -> Logger)
Because a singleton logger service is useful everywhere in the app,
it’s registered in
The @Injectable() annotation identifies a service class or
top-level function as available to an
injector for instantiation. Generally speaking, an injector will report an
error when trying to instantiate a class that is not marked as
Injectors are also responsible for instantiating components
HeroesComponent. Why isn’t
HeroesComponent marked as
You can add it if you really want to. It isn’t necessary because the
HeroesComponent is already marked with
@Component, and this
annotation class (like
@Pipe, which you’ll learn about later)
is a subtype of Injectable. It is in
Injectable annotations that
identify a class as a target for instantiation by an injector.
Always include the parentheses
@Injectable(), not just
A metadata annotation must be either a reference to a
compile-time constant variable or a call to a constant
constructor such as
If you forget the parentheses, the analyzer will complain: “Annotation creation must have arguments”. If you try to run the app anyway, it won’t work, and the console will say “expression must be a compile-time constant”.
A service provider provides the concrete, runtime instance associated with a dependency token. The injector relies on providers to create instances of the services that the injector injects into components, directives, pipes, and other services.
You must register a service provider with an injector, or it won’t know how to create the service.
The next few sections explain the many ways you can register a provider.
There are many ways to provide something that implements
The most common way is to use ClassProvider:
But it’s not the only way.
You can configure the injector with alternative providers that can deliver a
You could provide a substitute class.
You could give it a provider that calls a logger factory function.
Any of these approaches might be a good choice under the right circumstances.
What matters is that the injector has a provider to go to when it needs a
Occasionally you’ll ask a different class to provide the service.
The following code tells the injector
to return a
BetterLogger when something asks for the
Provider for a class with dependencies
EvenBetterLogger could display the user name in the log message.
This logger gets the user from the injected
which is also listed in the app component’s
Suppose an old component depends upon an
OldLogger has the same interface as the
NewLogger, but for some reason
you can’t update the old component to use it.
When the old component logs a message with
you’d like the singleton instance of
NewLogger to handle it instead.
The dependency injector should inject that singleton instance
when a component asks for either the new or the old logger.
OldLogger should be an alias for
You certainly do not want two different
NewLogger instances in your app.
Unfortunately, that’s what you get if you try
To ensure that the same
NewLogger instance is provided for both
NewLogger, use ExistingProvider:
Sometimes it’s easier to provide a ready-made object rather than ask the injector to create it from a class.
Then you register the object using ValueProvider:
For more examples of
ValueProvider, see OpaqueToken.
Sometimes you need to create the dependent value dynamically, based on information you won’t have until the last possible moment. Maybe the information changes during the course of the browser session.
Suppose also that the injectable service has no independent access to the source of this information.
This situation calls for a factory provider.
To illustrate the point, add a new business requirement:
HeroService must hide secret heroes from normal users.
Only authorized users should see secret heroes.
HeroService needs a fact about the user.
It needs to know if the user is authorized to see secret heroes.
That authorization can change during the course of a single app session,
as when you log in a different user.
EvenBetterLogger, you can’t inject the
UserService into the
HeroService won’t have direct access to the user information to decide
who is authorized and who is not.
HeroService constructor takes a boolean flag to control display of secret heroes.
You can inject the
Logger, but you can’t inject the boolean
You’ll have to take over the creation of new instances of this
HeroService with a factory provider.
A factory provider needs a factory function:
HeroService has no access to the
UserService, the factory function does.
You inject both the
Logger and the
UserService into the factory provider
and let the injector pass them along to the factory function:
Notice that you captured the factory provider in a constant,
This extra step makes the factory provider reusable.
You can register the
HeroService with this constant wherever you need it.
In this sample, you need it only in the
where it replaces the previous
HeroService registration in the metadata
Here you see the new and the old implementation side-by-side:
When you register a provider with an injector, you associate that provider with a dependency injection token. The injector maintains an internal map from tokens to providers that it references when asked for a dependency.
In all previous examples, the token has been a class type and the provided value
an instance of that type. For example, you get a
HeroService directly from the
injector by supplying the
HeroService type as the token:
Similarly, when you define a constructor parameter of type
Angular knows to inject a
Sometimes the thing you want to inject is a string, list, map, or even a function. For example, what if you want to inject the app title?
You know that a value provider is appropriate in this case,
but what can you use as the token? You could use
String, but that won’t
work if your app depends on several such injected strings.
One solution is to define and use an OpaqueToken:
The generic type argument, while optional, conveys the dependency’s type to developers
and tooling (not to be confused with the
OpaqueToken constructor argument type,
which is always
OpaqueToken argument token description is a developer aid.
Register the dependency provider using the
Now you can inject the title into any constructor that needs it, with the help of an @Inject() annotation:
Alternatively you can directly use the
OpaqueToken constant as an annotation:
You can inject values other than strings. For example, apps sometimes have configuration objects with lots of simple properties captured as a Map:
Custom configuration class
As an alternative to injecting a Map for an app configuration object, consider defining a custom app configuration class:
Defining a configuration class has a few benefits. One key benefit
is strong static checking: you’ll be warned early if you misspell a property
name or assign to it a value of the wrong type.
The Dart cascade notation (
..) provides a convenient means of initializing
a configuration object.
You might use the app config like this:
HeroService requires a
Logger, but what if it could get by without
You can tell Angular that the dependency is optional by annotating the
constructor argument with @Optional():
@Optional(), your code must be prepared for a null value. If you
don’t register a logger somewhere up the line, the injector will set the
logger to null.
You learned the basics of Angular dependency injection in this page. You can register various kinds of providers, and you know how to ask for an injected object (such as a service) by adding a parameter to a constructor.
Angular dependency injection is more capable than this page has described. You can learn more about its advanced features, beginning with its support for nested injectors, in Hierarchical Dependency Injection.
Appendix: Working with injectors directly
Developers rarely work directly with an injector, but
InjectorComponent that does.
Injector is itself an injectable service.
In this example, Angular injects the component’s own
Injector into the component’s constructor.
The component then asks the injected injector for the services it wants in
Note that the services themselves are not injected into the component.
They are retrieved by calling
get() method throws an error if it can’t resolve the requested service.
You can call
get() with a second parameter, which is the value to return if the service
is not found. Angular can’t find the service if it’s not registered with this or any ancestor injector.
This technique is an example of the service locator pattern.
Avoid this technique unless you genuinely need it. It encourages a careless grab-bag approach such as you see here. It’s difficult to explain, understand, and test. You can’t know by inspecting the constructor what this class requires or what it will do. It could acquire services from any ancestor component, not just its own. You’re forced to spelunk the implementation to discover what it does.
Framework developers may take this approach when they must acquire services generically and dynamically.