Injectable & DI Basics — Series 2

Preview — 3 of 10 questions

What does listing a bare class in providers mean?

javascript
@Module({ providers: [CatsService] })
export class CatsModule {}

// equivalent to:
@Module({ providers: [{ provide: CatsService, useClass: CatsService }] })
export class CatsModule {}
AIt is shorthand for a class provider whose injection token is the class itself and whose implementation is that same class
BIt registers the class as a controller if it has route decorators, and as a provider otherwise
CIt creates a new instance of the class for every injection site
DIt exports the class automatically to every module that imports this one

What happens at startup?

javascript
@Module({ controllers: [CatsController] }) // CatsService not listed
export class CatsModule {}

@Controller('cats')
export class CatsController {
  constructor(private readonly catsService: CatsService) {}
}
ANest instantiates CatsService automatically, since the constructor's type annotation is enough to locate the class
BThe application fails to start with Nest can't resolve dependencies of the CatsController (?), naming the missing argument and the module context to check
CThe application starts, and this.catsService is undefined until the first request
DNest falls back to a no-op stub whose methods all return null

Is this allowed, and what does it require?

javascript
@Injectable()
export class CatsService {
  constructor(private readonly logger: LoggerService) {}
}
ANo — only controllers may inject providers; services must instantiate their own dependencies with new
BYes, but only if LoggerService is declared @Global()
CYes — providers can inject other providers exactly like controllers do, as long as LoggerService is resolvable from this module
DYes, but the injected service is a fresh instance created specifically for CatsService

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.