You: Dependency injection (DI) is a design pattern in which an object receives other objects that it depends on (its dependencies) instead of creating them itself. This inverts the typical control flow, where the object would be responsible for creating or locating its dependencies. DI promotes loose coupling, making code more modular, testable, and maintainable.
Core Concepts:
1. Dependencies: These are the objects that a class or module needs to function correctly.
2. Injection: The act of providing these dependencies to the class or module.
3. Inversion of Control (IoC): Instead of the class creating its dependencies, they are provided externally.
How Dependency Injection Works:
There are several ways to implement dependency injection:
1. Constructor Injection:
- Dependencies are provided through the class constructor.
- This is the most common and recommended type of dependency injection.
- It makes dependencies explicit, as they are listed in the constructor.
Example:
```javascript
class UserService {
constructor(userRepository, emailService) {
this.userRepository = userRepository;
this.emailService = emailService;
}
createUser(userData) {
const user = this.userRepository.save(userData);
this.emailService.sendWelcomeEmail(user.email);
return user;
}
}
// Usage:
const userRepository = new UserRepository();
const emailService = new EmailService();
const userService = new UserService(userRepository, emailService);
```
In this example, `UserService` depends on `UserRepository` and `EmailService`. These dependencies are injected through the constructor.
2. Setter Injection:
- Dependencies are provided through setter methods (methods that set a property).
- This allows for optional dependencies, as they are not required at the time of object creation.
Example:
```javascript
class ProductService {
constructor() {
this.discountService = null; /Optional dependency */
}
setDiscountService(discountService) {
this.discountService = discountServi....
Log in to view the answer