Discover how NestJS can handle your app's wiring so you don't have to!
Why Dependency injection basics in NestJS? - Purpose & Use Cases
Imagine building a large NestJS app where every service manually creates its own dependencies using new. You have to update many places if a dependency changes.
Manually creating dependencies leads to tangled code, hard-to-test services, and lots of repeated setup. It's easy to make mistakes and hard to change things later.
Dependency injection lets NestJS automatically provide the right dependencies to your classes. You just declare what you need, and NestJS handles the rest.
class UserService {
constructor() {
this.repo = new UserRepository();
}
}@Injectable()
class UserService {
constructor(private readonly repo: UserRepository) {}
}This makes your code cleaner, easier to test, and flexible to change without rewriting everything.
When switching from a mock database to a real one, you just change the provider setup once, and all services get the new database automatically.
Manual dependency creation causes tangled, hard-to-maintain code.
Dependency injection automates providing dependencies to classes.
This leads to cleaner, testable, and flexible applications.