“Giving an object its instance variables” is a quote by James Shore to summarize DI. Using DI, an object or function receives other object or functions it depends on instead of creating them internally. It leads to loosely coupled structure.
Example
Without DI:
class UserServiceWithoutDI {
private logger: Logger;
constructor() {
this.logger = new Logger();
}
createUser(name: string): void {
this.logger.log(`User created: ${name}`);
}
}
// Usage
const userServiceWithoutDI = new UserServiceWithoutDI();
userServiceWithoutDI.createUser("Bob");
Using DI, logger
instance is created outside and then passed:
class Logger {
log(message: string): void {
console.log(`Log: ${message}`);
}
}
class UserService {
constructor(private logger: Logger) {}
createUser(name: string): void {
this.logger.log(`User created: ${name}`);
}
}
const logger = new Logger();
const userService = new UserService(logger);
userService.createUser("Alice");