Property-based injection in NestJS uses the @Inject() decorator directly at class properties instead of through the constructor.

Usage

import { Injectable, Inject } from '@nestjs/common';
 
@Injectable()
export class HttpService<T> {
  @Inject('HTTP_OPTIONS')
  private readonly httpClient: T;
}

When to use

Property-based injection is useful in specific scenarios:

  • Inheritance chains: When a base class requires dependencies and passing them through super() in all subclasses becomes cumbersome
  • Optional dependencies: When a dependency should be optional
  • Circular dependencies: As one approach to breaking circular dependency cycles

Trade-offs

Disadvantages:

  • Less clear than Constructor-based Injection
  • Dependencies not visible in constructor signature
  • Harder to understand class requirements
  • Cannot use readonly with initial value in TypeScript

When to avoid: If your class doesn’t extend another class, prefer Constructor-based Injection for better code clarity and maintainability.

Example use case

// Base class needing injection
export abstract class BaseController {
  @Inject('LOGGER')
  protected logger: Logger;
}
 
// Subclasses automatically get logger without passing to super()
export class CatsController extends BaseController {
  // Logger is available via @Inject() in base class
}