Bird
Raised Fist0
NestJSframework~5 mins

Dependency injection basics in NestJS

Choose your learning style10 modes available
Introduction

Dependency injection helps you give parts of your app what they need without making them find it themselves. It keeps your code clean and easy to change.

When you want to share a service like a database connection across different parts of your app.
When you want to make your code easier to test by swapping real services with fake ones.
When you want to organize your app so each part only focuses on its job.
When you want to avoid creating objects manually and let NestJS handle it for you.
Syntax
NestJS
import { Injectable } from '@nestjs/common';

@Injectable()
export class MyService {
  getHello(): string {
    return 'Hello!';
  }
}

import { Controller, Get } from '@nestjs/common';

@Controller()
export class MyController {
  constructor(private readonly myService: MyService) {}

  @Get()
  getHello(): string {
    return this.myService.getHello();
  }
}

@Injectable() marks a class as a service that can be injected.

The service is added to the constructor of the class that needs it, and NestJS provides it automatically.

Examples
This is a simple service that logs messages to the console.
NestJS
import { Injectable } from '@nestjs/common';

@Injectable()
export class LoggerService {
  log(message: string) {
    console.log(message);
  }
}
The controller uses the LoggerService injected via the constructor to log a message before returning a response.
NestJS
import { Controller, Get } from '@nestjs/common';
import { LoggerService } from './logger.service';

@Controller('hello')
export class HelloController {
  constructor(private readonly logger: LoggerService) {}

  @Get()
  sayHello(): string {
    this.logger.log('Saying hello');
    return 'Hello World!';
  }
}
Sample Program

This simple NestJS app shows dependency injection by providing GreetingService to AppController. When you visit the root URL, it returns a greeting message from the service.

NestJS
import { Injectable, Controller, Get, Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';

@Injectable()
class GreetingService {
  getGreeting(): string {
    return 'Hello from GreetingService!';
  }
}

@Controller()
class AppController {
  constructor(private readonly greetingService: GreetingService) {}

  @Get()
  getGreeting(): string {
    return this.greetingService.getGreeting();
  }
}

@Module({
  controllers: [AppController],
  providers: [GreetingService],
})
class AppModule {}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
  console.log('Application is running on http://localhost:3000');
}

bootstrap();
OutputSuccess
Important Notes

Always mark services with @Injectable() so NestJS can inject them.

Use constructor injection to get services where you need them.

Dependency injection helps keep your code easy to test and maintain.

Summary

Dependency injection lets NestJS provide needed services automatically.

Mark services with @Injectable() and inject them via constructors.

This keeps your code clean, testable, and organized.

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