Recall & Review
beginner
What is constructor injection in NestJS?
Constructor injection is a way to provide dependencies to a class by declaring them as parameters in the class constructor. NestJS automatically creates and passes these dependencies when creating the class instance.Click to reveal answer
intermediate
How does NestJS know which dependencies to inject in the constructor?
NestJS uses TypeScript's metadata and decorators to identify the types of the constructor parameters. It then looks for providers registered for those types and injects them automatically.
Click to reveal answer
beginner
Show a simple example of constructor injection in a NestJS service.
@Injectable()
export class CatsService {
constructor(private readonly dogsService: DogsService) {}
}
Here, DogsService is injected into CatsService via the constructor.Click to reveal answer
intermediate
Why is constructor injection preferred over manual creation of dependencies?
Constructor injection helps keep code clean and testable by letting NestJS manage dependencies. It avoids tight coupling and makes swapping or mocking dependencies easier.
Click to reveal answer
intermediate
What happens if a dependency is not registered as a provider but used in constructor injection?
NestJS will throw a runtime error saying it cannot resolve the dependency. All injected dependencies must be registered as providers in a module.
Click to reveal answer
In NestJS, how do you declare a dependency to be injected via constructor injection?
✗ Incorrect
Constructor injection requires declaring dependencies as constructor parameters with access modifiers so NestJS can inject them automatically.
What decorator must a class have to be injectable in NestJS?
✗ Incorrect
The @Injectable() decorator marks a class as a provider that can be injected via constructor injection.
If a dependency is missing from the providers array in a module, what will happen during constructor injection?
✗ Incorrect
All dependencies must be registered as providers; otherwise, NestJS throws an error at runtime.
Which of these is a benefit of constructor injection in NestJS?
✗ Incorrect
Constructor injection helps testability by allowing dependencies to be replaced with mocks during testing.
How does NestJS identify which instance to inject for a constructor parameter?
✗ Incorrect
NestJS uses TypeScript's type metadata to match constructor parameters to registered providers.
Explain constructor injection in NestJS and why it is useful.
Think about how NestJS creates class instances with needed services.
You got /3 concepts.
Describe what happens if you forget to register a dependency as a provider but try to inject it in a constructor.
Consider how NestJS finds dependencies to inject.
You got /3 concepts.