Dependency Injection
What is DI?
– DI is a design pattern that enables us to develop loosely coupled code, it is also
one of the most misunderstood concepts in the object oriented programming.
– The Dependency injection pattern is strictly related to SOLID principles
– Dependencies are services or objects that a class needs to perform its function
DI involves 3 types of classes
– Client Class : The client class (dependent class) is a class which depends on the
service class
– Service Class : The service class (dependency) is a class that provides service to
the client
– Injector Class : The injector class injects the service class object into the client
class
Client Service
Injector
Uses
Injects
Types of DI
– Constructor Injection: Injector supplies the service (dependency) through the
client class constructor.
– Property Injection: (aka the Setter Injection) the injector supplies the
dependency through a public property of the client class.
– Method Injection: (aka the Interface Injection) the client class implements an
interface which declares the method(s) to supply the dependency and the
injector uses this interface to supply the dependency to the client class.
DI Responsibilities
– Create the objects
– Know which classes require those objects
– And provide them all those objects
DI in Angular
– Angular has its own DI framework, which is typically used in the design of
Angular applications to increase their efficiency and modularity. A dependency
in Angular can be a class, referred as a service or even a simple object. Angular’s
Dependency Injection is based on providers, injectors, and tokens.
DI in Angular Components
– Token: This uniquely identifies something that we want injected.
A dependancy of our code.
– Dependancy: The actual code we want injected.
– Provider: This is a map between a token and a list of dependancies.
– Injector: This is a function which when passed a token returns
a dependancy (or a list of dependencies)
Reasons for use Dependency
Injection
– Decoupling: dependency injection makes your modules less coupled resulting in
a more maintainable codebase
– Easier unit testing: instead of using hardcoded dependencies you can pass
them into the module you would like to use
– Faster development: with dependency injection, after the interfaces are
defined it is easy to work without any conflicts
Thank You !