Nest: Question: Inject class by identifier for interfaces

Created on 5 May 2017  路  3Comments  路  Source: nestjs/nest

Hi,

is it possible to configure the dependency injector that I can map a typescript interface to a specific class?

Example:

@Controller('registration')
export class RegistrationController {

  private readonly registrationService: RegistrationService;

  constructor(registrationService: IRegistrationService) {
    this.registrationService = registrationService;
  }
export interface IRegistrationService {
  register(): void;
}
export class RegistrationService implements IRegistrationService {
  public register(): void {
    // ...
 }
}

How can I tell my module that for the IRegistrationService I'd like to inject the RegistrationService class?

In AngularJS I could use a string as identifier and use an @Inject decorator on the constructor parameter of the controller class

Example:

@ngModule({
  providers: [
    {provide: 'RegistrationService', useClass: RegistrationService},
  ],
})
export class RegistrationModule {
}
@Controller('registration')
export class RegistrationController {

  private readonly registrationService: RegistrationService;

  constructor(@Inject('RegistrationService') registrationService: IRegistrationService) {
    this.registrationService = registrationService;
  }

Is this possible?

Most helpful comment

Hi @JulianBiermann
It works same as in Angular. Take a look
https://kamilmysliwiec.gitbooks.io/nest/content/dependency-injection.html
Custom providers section

All 3 comments

Hi @JulianBiermann
It works same as in Angular. Take a look
https://kamilmysliwiec.gitbooks.io/nest/content/dependency-injection.html
Custom providers section

Thanks alot!

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings