What is Dependency Injection?
Dependency Injection (DI) is a programming design pattern that?makes a class independent of its dependencies. It achieves that by separating?object creation?from?object usage.
With Dependency Injection, classes are more focused on their core functionality, and they don’t have to worry about the details of how objects are created or configured. Instead, the objects are created and configured outside the class, and they are passed to the class as dependencies.
Many popular frameworks such as Angular, NestJS, and Spring use Dependency Injection as a core principle. By using it, these frameworks make it easier to manage complex applications with a large number of dependencies.
It improves the flexibility of the code and makes it easier to maintain.
Example
Imagine an application?Logger?class that has one method called?log?which simply logs a message to the console.
class Logger {
log(message: string) {
console.log(message);
}
}
The?UserService?class has a private property called?logger?which is an instance of the?Logger?class. It also has a constructor which accepts an instance of the?Logger?class as an argument and assigns it to the?logger?property.
class UserService {
private logger: Logger;
constructor(logger: Logger) {
this.logger = logger;
}
}
We then create a method called?getUsers?which logs the message "Getting users..." using the?log?method of the?Logger?instance.
class UserService {
private logger: Logger;
constructor(logger: Logger) {
this.logger = logger;
}
getUsers() {
this.logger.log('Getting users...');
// Get users logic
}
}
Next, we create a new instance of the?Logger?class and store it in the?logger?constant. Then, a new instance of the?UserService?class is created and passed the?logger?instance as an argument.
领英推荐
const logger = new Logger();
const userService = new UserService(logger);
Finally, the?getUsers?method of the?userService?instance is called, which logs the message "Getting users..." to the console using the?log?method of the?Logger?instance.
class Logger {
log(message: string) {
console.log(message);
}
}
class UserService {
private logger: Logger;
constructor(logger: Logger) {
this.logger = logger;
}
getUsers() {
this.logger.log('Getting users...');
// Get users logic
}
}
const logger = new Logger();
const userService = new UserService(logger);
userService.getUsers(); // Getting users...
This demonstrates how the?UserService?class depends on the?Logger?class to log messages.
In this case, an instance of the?Logger?class is injected into the?UserService?instance's constructor using dependency injection.
Advantages and Disadvantages of DI
Dependency Injection has several advantages and disadvantages:
Advantages:
Disadvantages:
Overall, the advantages of DI often outweigh the disadvantages, especially in larger applications where modular design and testability are important.