Dependency Injection or in an abbreviation, DI is an application pattern used to develop and design angular based application for a better approach and greater efficiency. Few software developers believe Dependency Injection to be objects or services required by classes to perform a significant function. When classes prefer taking help from external sources, instead of creating one by itself, it looks up for dependencies and the concept – Dependency Injection in Angular.
DI can also be named as an angular framework that entails an instantiated class with declared dependencies. Now if you are wondering how all of this works, then here we are to give a flavor of DI in angular.
DI – The Idea Behind
For years, developers have been using the concept of injecting dependency in their angular application. Now the fact that such an integration eliminates the need for Angular developers to know about how those dependencies were created or how they work, add to the popularity of the DI framework.
Also Read: Why Use Angular?
Dependency Injection as a Pattern
As specified above, we see dependency injection to be the angular pattern that can be embedded in classes as and when required. For instance, consider the following example:
class Bike { constructor() { this.engine = new Engine(); this.tires = Tires.getInstance(); this.mirror = app.get('mirrors'); } }
Now, here you see that we have a class named Bike with three variables. A constructor that helps us assign each to the required variable so as to finally draft our bike object. Isn’t it? But did you notice that everything here is so complex, I mean, Engine object is created using a constructor, tires act as singleton class whereas mirror is fetched using a global object. So in a way, classes do define internal dependencies and at the same time, know-how these are created. Right?
Well, for some this might be beneficial but consider that you need to test the object. Like every time you need to test a mock engine, you would need to replace the code. This is nothing but overhead. Of course, you won’t sit and manually keep replacing the code in every test case. Here is where the idea of dependency injection comes into view.
We need to have one environment that could seamlessly work in all conditions and test codes, meaning that your testable code is reusable code.
Try this:
class Bike { constructor(engine, tires, mirrors) { this.engine = engine; this.tires = tires; this.mirrors = mirrors; } }
What we sought to do here is eliminate the dependency from constructors while extending the functionality of constructors to get all that’s needed. Simple?
The next time you need to create a bike object, you would simply need to pass needed dependencies.
var bike = new Bike( new Engine(), new Tires(), new Mirrors() );
Or,
var bike = new Bike( new MockEngine(), new MockTires(), new MockMirrors() );
This is dependency injection in the form of a pattern, or to be precise, constructor injection.
One thing to note here is, how do we manage to assemble the dependencies considering that we have shifted that from constructor to external level.
function main() { var engine = new Engine(); var tires = new Tires(); var mirrors = new Mirrors(); var bike = new Bike (engine, tires, mirrors); bike.ride(); }
This function would definitely help you take over the need to assemble dependencies but here again, doing all of this manually is a bit cumbersome. What do you think about this?
function main() { var injector = new Injector(...) var bike = injector.get(Bike); bike.ride(); }
So, as the application gets bigger and bigger, using injectors is an ideal way to handles dependencies.
Dependency Injection As A Framework
The above-stated code was an instance of using Dependency Injection as a framework. Angular one has its own DI system that enables developers to automate services and components, leaving the task of identification on injectors.
So, it’s the injectors that need to determine when and which dependency has to be initiated
class Bike { ... } Bike.$inject = ['Engine', 'Tires', 'Mirrors']
So, the next time you register your bike in terms of service and ask for it, you would get a singleton instance and yes, you aren’t required to be wary about creating dependencies.
var app = angular.module('myApp', []); app.service('Bike', bike); app.service('OtherService', function (Bike) { // instance of Bike available });
All of this looks good and pretty enticing, but nothing is perfect. There are a few issues within this system and its time to identify them before seeing how to solve them.
Problems
- The instance created one application per life cycle
- Namespace collision
- Cannot be decoupled in a standalone environment
These have been addressed in angular 2 and so we come up to the discussion of Dependency Injection in Angular.
DI in Angular
The updated version of DI in angular has three components:
- Injector – The object of injector exposes APIs needed to build instances of dependencies.
- Provider – This is more of a recipe guiding the injector on ways of creation of dependency instances. It is the provider that takes a specific token and further maps the same to the factory function so as to creates the object.
- Dependency – It is the type that accounts for object creation.
Integrating all of the above three components, we implement the bike object.
import { ReflectiveInjector } from '@angular/core'; var injector = ReflectiveInjector.resolveAndCreate([ Bike, Engine, Tires, Mirrors ]); var bike = injector.get(Bike);
- The ReflectiveInjector is imported from Angular and is the injector implementation which is responsible for exposing the static APIs to lead to the creation of injectors.
- resolve and create() is our factory function which would create the injector and then accept a list of providers.
- injector.get() To know how the injector gets an idea on the dependencies required for the instantiation of the bike?
import { Inject } from '@angular/core'; class Bike { constructor( @Inject(Engine) engine, @Inject(Tires) tires, @Inject(Mirrors) mirrors ) { … } }
We further import Inject from the framework, using it as the decorator to our constructor parameters. What the Inject decorator does it attach the metadata to our Bike class, which further gets used by DI.
We can rewrite the above code to Typescript as:
class Bike { constructor(engine: Engine, tires: Tires, mirrors: Mirrors) { ... } }
Now, this good as the class creates its own dependencies and DI can know about when to create what. But, how would the injector know about instance creation?
var injector = ReflectiveInjector.resolveAndCreate([ Bike, Engine, Tires, Mirrors ]);
So, we do this to let the injector know how to create the instance and is the list of providers that we needed to pass.
In case you are in a dilemma that how to do the above works,
var injector = RelfectiveInjector.resolveAndCreate([ { provide: Bike, useClass: Bike}, { provide: Engine, useClass: Engine }, { provide: Tires, useClass: Tires }, { provide: Mirrors, useClass: Mirrors } ]);
What we wrote above was the shorthand form of the original code. This helps us eliminate the issues of namespace collision as we can map a token to anything.
For instance:
{ provide: Engine, useClass: OtherEngine}
Got it?
Conclusion
So, this was all about how DI works in angular, what the drawbacks of the system were then and how the modified version of dependency injection in angular development deals with all. No more singleton instance, no namespace collision, and the efficiency increased multiple times. Remember, the idea is to do better and bigger using AngularJS development services to increase the effectiveness of the end product.