0
0
NestJSframework~3 mins

Why Dependency injection basics in NestJS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how NestJS can handle your app's wiring so you don't have to!

The Scenario

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.

The Problem

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.

The Solution

Dependency injection lets NestJS automatically provide the right dependencies to your classes. You just declare what you need, and NestJS handles the rest.

Before vs After
Before
class UserService {
  constructor() {
    this.repo = new UserRepository();
  }
}
After
@Injectable()
class UserService {
  constructor(private readonly repo: UserRepository) {}
}
What It Enables

This makes your code cleaner, easier to test, and flexible to change without rewriting everything.

Real Life Example

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.

Key Takeaways

Manual dependency creation causes tangled, hard-to-maintain code.

Dependency injection automates providing dependencies to classes.

This leads to cleaner, testable, and flexible applications.