Bird
Raised Fist0
NestJSframework~10 mins

Dependency injection basics in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Dependency injection basics
Define Service Class
↓
Register Service in Module
↓
Inject Service into Consumer
↓
Use Service Methods
↓
NestJS Provides Instance Automatically
This flow shows how a service is created, registered, injected, and used automatically by NestJS.
Execution Sample
NestJS
import { Injectable } from '@nestjs/common';

@Injectable()
export class CatsService {
  getCats() { return ['Tom', 'Jerry']; }
}
Defines a simple service class that NestJS can inject where needed.
Execution Table
StepActionEvaluationResult
1Define CatsService with @Injectable()NestJS marks it as injectableCatsService class ready for injection
2Register CatsService in AppModule providersNestJS adds it to the containerCatsService instance managed by NestJS
3Inject CatsService into CatsController constructorNestJS finds provider and injects instanceCatsController has CatsService instance
4Call catsService.getCats() in controller methodMethod returns ['Tom', 'Jerry']Controller returns cat list
5Request handled with injected service dataResponse sent with cat namesExecution complete
💡 All steps complete; service injected and used successfully
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
CatsServiceundefinedDefined class with methodRegistered in containerInstance injected in controllerMethod called returns arrayInstance used to respond
Key Moments - 3 Insights
Why do we add @Injectable() to the service class?
Because @Injectable() tells NestJS this class can be managed and injected. Without it, NestJS won't create or inject the service (see execution_table step 1).
How does NestJS know which instance to inject?
NestJS uses the providers registered in the module to find the matching class and injects the same instance wherever needed (see execution_table step 2 and 3).
What happens if we forget to register the service in the module?
NestJS will throw an error because it can't find the provider to inject (missing step 2 in execution_table).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result after step 3?
ACatsController has CatsService instance
BCatsService method returns array
CCatsService class is undefined
DRequest handled with cat names
💡 Hint
Check the 'Result' column in step 3 of execution_table
At which step does NestJS register the service in its container?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look for 'Registered in container' in the 'Result' column
If we remove @Injectable() from CatsService, what will happen?
ANestJS will still inject the service
BService methods will return empty arrays
CNestJS will throw an error at injection
DNothing changes
💡 Hint
Refer to key_moments about the role of @Injectable() and execution_table step 1
Concept Snapshot
Dependency Injection in NestJS:
- Mark classes with @Injectable() to make them injectable.
- Register services in module providers.
- Inject services via constructor in consumers.
- NestJS creates and shares instances automatically.
- Enables easy reuse and testing.
Full Transcript
Dependency injection in NestJS means creating service classes marked with @Injectable(), registering them in a module's providers array, and then injecting them into other classes like controllers via constructor parameters. NestJS automatically creates and shares instances of these services. This process helps organize code and makes it easy to reuse and test. The execution flow starts with defining the service, registering it, injecting it, and finally using its methods to handle requests.

Practice

(1/5)
1. What is the main purpose of dependency injection in NestJS?
easy
A. To automatically provide required services to classes
B. To manually create instances of services inside components
C. To write all code inside a single file
D. To avoid using classes and use only functions

Solution

  1. Step 1: Understand dependency injection concept

    Dependency injection means NestJS automatically gives the needed services to classes without manual creation.
  2. 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.
  3. Final Answer:

    To automatically provide required services to classes -> Option A
  4. Quick Check:

    Dependency injection = automatic service provision [OK]
Hint: Dependency injection means NestJS gives services automatically [OK]
Common Mistakes:
  • Thinking you must create service instances manually
  • Confusing dependency injection with code organization only
  • Believing dependency injection removes classes
2. Which decorator marks a class as injectable for NestJS dependency injection?
easy
A. @Module()
B. @Controller()
C. @Injectable()
D. @Service()

Solution

  1. Step 1: Recall NestJS decorators for DI

    Classes that can be injected must be marked with @Injectable() decorator.
  2. Step 2: Check each option

    @Controller is for controllers, @Module for modules, @Service is not a NestJS decorator.
  3. Final Answer:

    @Injectable() -> Option C
  4. Quick Check:

    @Injectable() marks injectable classes [OK]
Hint: Use @Injectable() to mark services for injection [OK]
Common Mistakes:
  • Using @Controller or @Module instead of @Injectable
  • Assuming @Service is a valid NestJS decorator
  • Forgetting to add any decorator
3. Given this code snippet, what will be the output when 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();
  }
}
medium
A. Error: AppService not provided
B. 'Hello from AppService'
C. undefined
D. 'Hello from AppController'

Solution

  1. Step 1: Understand injection in constructor

    AppController receives AppService instance via constructor injection because AppService is marked @Injectable.
  2. Step 2: Trace method call

    showMessage calls appService.getMessage(), which returns 'Hello from AppService'.
  3. Final Answer:

    'Hello from AppService' -> Option B
  4. Quick Check:

    Injected service method returns message [OK]
Hint: Injected service methods return their defined values [OK]
Common Mistakes:
  • Assuming injection fails without @Module setup
  • Expecting AppController message instead
  • Confusing method return values
4. Identify the error in this NestJS service injection code:
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();
  }
}
medium
A. UserService is missing @Injectable() decorator
B. UserController should not have a constructor
C. fetchUser method should be async
D. userService property should be public

Solution

  1. Step 1: Check decorators on injectable classes

    UserService is injected into UserController but lacks @Injectable(), so NestJS cannot inject it.
  2. Step 2: Verify other options

    Constructor in controller is valid, fetchUser need not be async, and private readonly is correct for injection.
  3. Final Answer:

    UserService is missing @Injectable() decorator -> Option A
  4. Quick Check:

    Injectable classes must have @Injectable() [OK]
Hint: Injectable services must have @Injectable() decorator [OK]
Common Mistakes:
  • Forgetting @Injectable on services
  • Thinking constructor is invalid in controllers
  • Assuming async is required for injected methods
5. You want to inject two different services, LoggerService and ConfigService, into a controller. Which is the correct way to do this in NestJS?
hard
A. Inject only one service and import the other directly
B. Create instances manually inside the controller constructor
C. Use @Injectable() on the controller and call services statically
D. Use constructor injection with both services as parameters marked private readonly

Solution

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

    Use constructor injection with both services as parameters marked private readonly -> Option D
  4. Quick Check:

    Multiple services injected via constructor parameters [OK]
Hint: Inject multiple services by listing them in constructor [OK]
Common Mistakes:
  • Manually creating service instances inside controllers
  • Using static calls instead of injection
  • Injecting only one service when multiple are needed
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