nest icon indicating copy to clipboard operation
nest copied to clipboard

Can't inject services into module with @Inject

Open JulianRuhrDev opened this issue 9 years ago • 3 comments

Hi,

it looks like I'm not able to inject a service into my module when I'm using the @Inject decorator.

Following code is throwing an resolve error:

@Module({
  controllers: [
    AuthenticationController,
  ],
  components: [
    {provide: 'AuthenticationService', useClass: HttpBasicAuthenticationService},
  ],
})
export class AuthenticationModule implements NestModule {

  private readonly authenticationService: IAuthenticationService;

  constructor(
    @Inject('AuthenticationService') authenticationService: IAuthenticationService,
  ) {
    this.authenticationService = authenticationService;
  }
}

Error:

[Nest] 10638   - 2017-5-5 15:17:32   [ExceptionHandler] Nest could not resolves dependencies of AuthenticationModule.
Error: Nest could not resolves dependencies of AuthenticationModule.

The service class is decorated with the @Component decorator.

JulianRuhrDev avatar May 05 '17 13:05 JulianRuhrDev

I could track down the error to the module class.

    addCustomClass(component) {
        const { provide: metatype, useClass } = component;

        this._components.set(metatype.name, {
            name: metatype.name,
            metatype: useClass,
            instance: null,
            isResolved: false,
        });
    }

The incoming metatype is a string and does not have a name property which results in an undefined set entry.

I tested around and changed it to the following:

    addCustomClass(component) {
        const { provide: metatype, useClass } = component;
        let name = metatype.name;
        if (!name) {
            name = metatype;
        }
        this._components.set(name, {
            name: name,
            metatype: useClass,
            instance: null,
            isResolved: false,
        });
    }

This is a quick hack but it fixes the problem. Now the injector can resolve the dependency. I guess you'r using the name property if a constructor is given in the provide property of the component?

JulianRuhrDev avatar May 05 '17 14:05 JulianRuhrDev

Hi @JulianBiermann

Thank you for reporting. Issue is already fixed, please, update package into v. 1.0.3.

kamilmysliwiec avatar May 05 '17 14:05 kamilmysliwiec

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]