nest icon indicating copy to clipboard operation
nest copied to clipboard

Question: Inject class by identifier for interfaces

Open JulianRuhrDev opened this issue 9 years ago • 3 comments

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?

JulianRuhrDev avatar May 05 '17 12:05 JulianRuhrDev

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

kamilmysliwiec avatar May 05 '17 12:05 kamilmysliwiec

Thanks alot!

JulianRuhrDev avatar May 05 '17 12:05 JulianRuhrDev

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.

lock[bot] avatar Sep 25 '19 13:09 lock[bot]