EG
Resume
·backend·
#nestjs#backend#typescript#di

okay so NestJS dependency injection was confusing me for the longest time. here's what I wish someone told me earlier.

The Basic Idea

instead of creating objects manually everywhere, you just... ask for them. NestJS figures out where to get them and gives them to you.

// before DI - manual instantiation (pain)
class UserService {
  private userRepo = new UserRepository();
  private emailService = new EmailService();
}

// with DI - just ask for it (✨)
constructor(
  private userRepository: UserRepository,
  private emailService: EmailService,
) {}

NestJS automatically instantiates UserRepository and EmailService and gives them to you. magic? no, just DI.

The Token System

this confused me initially. why do we need tokens?

// when class name alone isn't enough
// use injection tokens

export const DATABASE_CONNECTION = 'DATABASE_CONNECTION';

// then use it
@Inject('DATABASE_CONNECTION')
private connection: any

useful for third-party stuff or when you need multiple instances of same type.

The @Inject() Decorator

required when:

  1. Using custom tokens
  2. Injecting something that can't be auto-detected
constructor(
  @Inject('CONFIG') private config: any,
  private userService: UserService, // auto-detected
) {}

Provider Scope (when stuff gets recreated)

Default (Singleton): one instance for entire app Request: new instance per request Transient: new instance every time it's injected

// request-scoped provider
@Injectable({ scope: Scope.REQUEST })
class MyService {}

rarely needed but useful for database connection per request.

The Module System

modules are just groups of related stuff:

@Module({
  providers: [UserService, UserRepository],
  exports: [UserService], // only export what others need
})
export class UserModule {}

injected where you need it, Nest handles the rest.

TL;DR

  • don't manually new anything
  • let Nest create and inject dependencies
  • use @Inject() only when necessary
  • understand providers, modules, and scopes
  • RTFM more (I'm still learning too lol)

still confused about some parts tbh. but getting better.

Related Articles