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?
ACall the dependency inside the constructor manually
BImport the dependency inside the constructor body
CUse a global variable for the dependency
DAdd it as a parameter in the constructor with an access modifier like private or public
✗ 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?
A@Module()
B@Controller()
C@Injectable()
D@Component()
✗ 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?
ANestJS throws an error that it cannot resolve the dependency
BNestJS injects a default empty object
CNestJS ignores the dependency and continues
DNestJS logs a warning but injects null
✗ 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?
AMakes code run faster by avoiding function calls
BImproves testability by allowing easy mocking of dependencies
CAutomatically generates UI components
DRemoves the need for modules
✗ 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?
ABy the type of the parameter using TypeScript metadata
BBy the parameter name as a string
CBy the order of parameters in the constructor
DBy scanning the file system for matching files
✗ 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.
Practice
(1/5)
1. What is the main purpose of constructor injection in NestJS?
easy
A. To provide required services to a class when it is created
B. To manually create instances of services inside methods
C. To define routes for HTTP requests
D. To write database queries inside the constructor
Solution
Step 1: Understand constructor injection concept
Constructor injection is used to pass dependencies (services) into a class automatically when it is created.
Step 2: Identify the purpose in NestJS context
In NestJS, constructor injection helps keep code clean by providing needed services without manual instantiation.
Final Answer:
To provide required services to a class when it is created -> Option A
Quick Check:
Constructor injection = provide services automatically [OK]
Hint: Constructor injection means passing services via constructor [OK]
Common Mistakes:
Thinking constructor injection creates routes
Manually creating service instances inside methods
Confusing injection with database queries
2. Which of the following is the correct syntax for constructor injection of a service named UsersService in a NestJS class?
easy
A. constructor(private readonly usersService: UsersService) {}
B. constructor(usersService: UsersService) {}
C. constructor(private usersService) {}
D. constructor(public readonly usersService) {}
Solution
Step 1: Check for correct access modifier and typing
In NestJS, constructor injection requires private readonly with the service type for proper injection and immutability.
Step 2: Compare options
constructor(private readonly usersService: UsersService) {} (A) is correct. B misses access modifier, C misses type, D misses type annotation.
Final Answer:
constructor(private readonly usersService: UsersService) {} -> Option A
Quick Check:
Use private readonly with type for injection [OK]
Hint: Use 'private readonly serviceName: ServiceType' in constructor [OK]
Common Mistakes:
Omitting access modifier like private or public
Not specifying the service type
Using public readonly without specifying the service type
3. Given the following code, what will be the output when appController.getHello() is called?
The AppController receives HelloService via constructor injection and stores it as helloService.
Step 2: Trace method call
Calling getHello() calls helloService.getMessage() which returns 'Hello, NestJS!'.
Final Answer:
'Hello, NestJS!' -> Option C
Quick Check:
Injected service method returns 'Hello, NestJS!' [OK]
Hint: Injected service methods return expected values [OK]
Common Mistakes:
Assuming service is undefined without injection
Confusing method return values
Expecting default or unrelated strings
4. Identify the error in the following NestJS service injection code:
@Injectable()
class CatsService {}
@Controller('cats')
class CatsController {
constructor(catsService: CatsService) {}
findAll() {
return 'All cats';
}
}
medium
A. CatsService is not decorated with @Injectable()
B. Missing access modifier (private/public) in constructor parameter
C. Controller decorator is missing path
D. findAll method should be async
Solution
Step 1: Check constructor injection syntax
The constructor parameter catsService: CatsService lacks an access modifier like private or public, so it won't be assigned as a class property.
Step 2: Verify other parts
@Injectable() is present on service, @Controller('cats') has path, and findAll can be sync. So no other errors.
Final Answer:
Missing access modifier (private/public) in constructor parameter -> Option B
Quick Check:
Constructor injection needs access modifier [OK]
Hint: Always add private/public to constructor params for injection [OK]
Common Mistakes:
Omitting private/public in constructor injection
Thinking @Injectable is missing when it is present
Assuming controller path is mandatory for injection
5. You want to inject two services, AuthService and UsersService, into a NestJS controller. Which constructor correctly injects both services following best practices?
hard
A. constructor(public authService: AuthService, public usersService: UsersService) {}
B. constructor(authService: AuthService, usersService: UsersService) {}
C. constructor(private authService: AuthService, usersService: UsersService) {}
D. constructor(private readonly authService: AuthService, private readonly usersService: UsersService) {}
Solution
Step 1: Check for access modifiers and readonly usage
Best practice is to use private readonly for injected services to keep them immutable and private.
Step 2: Verify both services are injected with correct syntax
constructor(private readonly authService: AuthService, private readonly usersService: UsersService) {} injects both services with private readonly, while others miss modifiers or use public.