DI là technique mà object nhận dependencies từ bên ngoài thay vì tự tạo — là cơ chế triển khai DIP.
Ba loại DI:
// (1) Constructor Injection (phổ biến nhất)
class UserService {
constructor(private userRepo: UserRepository) {}
}
// (2) Setter/Property Injection (cho optional dependency)
class UserService {
setRepository(repo: UserRepository) { this.repo = repo }
}
// (3) Method Injection (chỉ cần cho một operation)
class UserService {
getUser(id: string, repo: UserRepository) { return repo.find(id) }
}Framework DI: NestJS dùng IoC container với decorators @Injectable(), @Inject() — tự động resolve dependency tree. Trong Go không có framework DI phổ biến, thường dùng manual DI qua wire (Google) hoặc constructor functions.
Lợi ích: loose coupling, dễ test (inject mock), dễ swap implementation. Anti-pattern: Service Locator (class tự gọi container.get('UserRepo')) — tạo hidden dependency.
DI is the technique where an object receives its dependencies from the outside rather than creating them — it is the mechanism that implements DIP.
Three types of DI:
// (1) Constructor Injection (most common)
class UserService {
constructor(private userRepo: UserRepository) {}
}
// (2) Setter/Property Injection (for optional dependencies)
class UserService {
setRepository(repo: UserRepository) { this.repo = repo }
}
// (3) Method Injection (dependency needed for one operation)
class UserService {
getUser(id: string, repo: UserRepository) { return repo.find(id) }
}DI frameworks: NestJS uses an IoC container with @Injectable() and @Inject() decorators that automatically resolve the dependency tree. Go has no dominant DI framework; manual DI via wire (Google) or plain constructor functions is the norm.
Benefits: loose coupling, easy testing (inject mocks), easy implementation swapping. Anti-pattern: Service Locator (a class calling container.get('UserRepo')) — creates hidden dependencies.