Why nestjs service is not injected into passport strategy?

Viewed 506

I'm trying to make application using nestjs

Dependency injection into controller works well so far.

But when I inject service into passport strategy, injecting is not working.

I want to inject authService into googleStrategy.

This is my module code.

auth.modules.ts

@Module({
  imports: [
    UsersModules,
    PassportModule,
  ],
  controllers: [AuthController],
  providers: [AuthService, GoogleStrategy],
})
export class AuthModules {}

google.strategy.ts

@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
  constructor(private authService: AuthService) {
    super({ /*...*/ });
    console.log(this.authService) //undefined
  }
}

In this case, AuthService is not injected.

When I inject AuthService manually using @Inject decorator, AuthService injected successfully.

constructor(@Inject('AuthService') private authService: AuthService) {
  super({ /*...*/ });
  console.log(this.authService) // AuthService is injected
}

Why service is not injected into passport strategy?

1 Answers

Try to register your AuthService in AuthModule like this:

providers: [
  {
    provide: 'AUTH_SERVICE',
    useClass: AuthService
  },
  GoogleStrategy
]

And then, in GoogleStrategy class, in constructor write this:

constructor(@Inject('AUTH_SERVICE') private authService: AuthService)
Related