Bird
Raised Fist0
NestJSframework~10 mins

Constructor injection in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Constructor injection
Define Service Class
↓
Add @Injectable Decorator
↓
Define Constructor with Dependency Parameter
↓
NestJS Creates Instance
↓
NestJS Injects Dependency into Constructor
↓
Service Ready to Use with Dependency
This flow shows how NestJS uses constructor injection to provide dependencies automatically when creating a service instance.
Execution Sample
NestJS
import { Injectable } from '@nestjs/common';

@Injectable()
export class DogsService {}

@Injectable()
export class CatsService {
  constructor(private readonly dogsService: DogsService) {}
}
This code defines a CatsService that receives DogsService via constructor injection.
Execution Table
StepActionEvaluationResult
1NestJS reads CatsService classFinds @Injectable decoratorMarks CatsService as injectable
2NestJS sees constructor parameter dogsServiceType is DogsServicePrepares to inject DogsService instance
3NestJS creates DogsService instanceDogsService is injectableDogsService instance ready
4NestJS calls CatsService constructorPasses DogsService instance as argumentCatsService instance created with dogsService
5CatsService readydogsService property setCan use dogsService methods inside CatsService
💡 Constructor injection completes when CatsService instance is created with DogsService dependency injected.
Variable Tracker
VariableStartAfter Step 3After Step 4Final
dogsServiceundefinedDogsService instance createdInjected into CatsService constructorAvailable as private readonly property
Key Moments - 3 Insights
Why do we add @Injectable() above the service class?
NestJS needs @Injectable() to know it can create and inject this class. Without it, injection won't work (see execution_table step 1).
How does NestJS know what to inject into the constructor?
NestJS uses the constructor parameter type (DogsService) to find or create the right instance to inject (see execution_table step 2 and 3).
What happens if the dependency is missing or not injectable?
NestJS will throw an error during instance creation because it can't resolve the dependency (not shown in table but happens before step 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what happens at step 3?
ANestJS creates an instance of DogsService
BNestJS calls CatsService constructor
CNestJS marks CatsService as injectable
DNestJS injects DogsService into CatsService
💡 Hint
Check the 'Action' and 'Result' columns at step 3 in the execution_table.
At which step is the DogsService instance passed into CatsService constructor?
AStep 1
BStep 2
CStep 4
DStep 5
💡 Hint
Look for the step where CatsService constructor is called with DogsService instance.
If we remove @Injectable() from CatsService, what will happen?
ANestJS will still inject DogsService without error
BNestJS will throw an error because CatsService is not injectable
CDogsService will not be created
DCatsService will be created but dogsService will be undefined
💡 Hint
Refer to key_moments about the role of @Injectable() and execution_table step 1.
Concept Snapshot
Constructor Injection in NestJS:
- Use @Injectable() on classes to enable injection.
- Declare dependencies as constructor parameters.
- NestJS creates and injects dependencies automatically.
- This helps keep code clean and testable.
- Missing @Injectable() causes injection errors.
Full Transcript
Constructor injection in NestJS means that when you create a service class, you add the @Injectable decorator so NestJS knows it can create it. Then you add dependencies as parameters in the constructor. When NestJS creates your service, it automatically creates and passes the dependencies into the constructor. This way, your service can use other services easily without manually creating them. If you forget the @Injectable decorator, NestJS will not inject dependencies and will throw an error. This process helps keep your code organized and easy to test.

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

  1. Step 1: Understand constructor injection concept

    Constructor injection is used to pass dependencies (services) into a class automatically when it is created.
  2. Step 2: Identify the purpose in NestJS context

    In NestJS, constructor injection helps keep code clean by providing needed services without manual instantiation.
  3. Final Answer:

    To provide required services to a class when it is created -> Option A
  4. 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

  1. 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.
  2. Step 2: Compare options

    constructor(private readonly usersService: UsersService) {} (A) is correct. B misses access modifier, C misses type, D misses type annotation.
  3. Final Answer:

    constructor(private readonly usersService: UsersService) {} -> Option A
  4. 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?
import { Injectable, Controller } from '@nestjs/common';

@Injectable()
class HelloService {
  getMessage() {
    return 'Hello, NestJS!';
  }
}

@Controller()
class AppController {
  constructor(private readonly helloService: HelloService) {}

  getHello() {
    return this.helloService.getMessage();
  }
}
medium
A. Error: helloService is not defined
B. undefined
C. 'Hello, NestJS!'
D. 'Hello, World!'

Solution

  1. Step 1: Understand constructor injection usage

    The AppController receives HelloService via constructor injection and stores it as helloService.
  2. Step 2: Trace method call

    Calling getHello() calls helloService.getMessage() which returns 'Hello, NestJS!'.
  3. Final Answer:

    'Hello, NestJS!' -> Option C
  4. 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

  1. 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.
  2. Step 2: Verify other parts

    @Injectable() is present on service, @Controller('cats') has path, and findAll can be sync. So no other errors.
  3. Final Answer:

    Missing access modifier (private/public) in constructor parameter -> Option B
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    constructor(private readonly authService: AuthService, private readonly usersService: UsersService) {} -> Option D
  4. Quick Check:

    Use private readonly for multiple injected services [OK]
Hint: Use private readonly for all injected services in constructor [OK]
Common Mistakes:
  • Omitting access modifiers on one or both services
  • Using public instead of private readonly
  • Mixing access modifiers inconsistently
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard