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.
Practice
Solution
Step 1: Understand dependency injection concept
Dependency injection means NestJS automatically gives the needed services to classes without manual creation.Step 2: Compare options with this concept
Only To automatically provide required services to classes describes automatic service provision, others describe manual or unrelated actions.Final Answer:
To automatically provide required services to classes -> Option AQuick Check:
Dependency injection = automatic service provision [OK]
- Thinking you must create service instances manually
- Confusing dependency injection with code organization only
- Believing dependency injection removes classes
Solution
Step 1: Recall NestJS decorators for DI
Classes that can be injected must be marked with @Injectable() decorator.Step 2: Check each option
@Controller is for controllers, @Module for modules, @Service is not a NestJS decorator.Final Answer:
@Injectable() -> Option CQuick Check:
@Injectable() marks injectable classes [OK]
- Using @Controller or @Module instead of @Injectable
- Assuming @Service is a valid NestJS decorator
- Forgetting to add any decorator
appService.getMessage() is called?import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getMessage() {
return 'Hello from AppService';
}
}
export class AppController {
constructor(private readonly appService: AppService) {}
showMessage() {
return this.appService.getMessage();
}
}Solution
Step 1: Understand injection in constructor
AppController receives AppService instance via constructor injection because AppService is marked @Injectable.Step 2: Trace method call
showMessage calls appService.getMessage(), which returns 'Hello from AppService'.Final Answer:
'Hello from AppService' -> Option BQuick Check:
Injected service method returns message [OK]
- Assuming injection fails without @Module setup
- Expecting AppController message instead
- Confusing method return values
import { Injectable } from '@nestjs/common';
export class UserService {
getUser() {
return 'User data';
}
}
@Injectable()
export class UserController {
constructor(private readonly userService: UserService) {}
fetchUser() {
return this.userService.getUser();
}
}Solution
Step 1: Check decorators on injectable classes
UserService is injected into UserController but lacks @Injectable(), so NestJS cannot inject it.Step 2: Verify other options
Constructor in controller is valid, fetchUser need not be async, and private readonly is correct for injection.Final Answer:
UserService is missing @Injectable() decorator -> Option AQuick Check:
Injectable classes must have @Injectable() [OK]
- Forgetting @Injectable on services
- Thinking constructor is invalid in controllers
- Assuming async is required for injected methods
LoggerService and ConfigService, into a controller. Which is the correct way to do this in NestJS?Solution
Step 1: Recall how to inject multiple services
In NestJS, multiple services are injected by listing them as constructor parameters with access modifiers like private readonly.Step 2: Evaluate options
Use constructor injection with both services as parameters marked private readonly correctly uses constructor injection. Create instances manually inside the controller constructor manually creates instances, breaking DI. Use @Injectable() on the controller and call services statically misuses @Injectable on controller and static calls. Inject only one service and import the other directly injects only one service, which is incomplete.Final Answer:
Use constructor injection with both services as parameters marked private readonly -> Option DQuick Check:
Multiple services injected via constructor parameters [OK]
- Manually creating service instances inside controllers
- Using static calls instead of injection
- Injecting only one service when multiple are needed
Ready to prove it?
Pass the test and this pattern moves unknown
