NestJS get exsiting instance of service when using useFacetory()

Viewed 28

I have a service class ServiceB which injecting ServiceA

export class ServiceB {
  constructor(
    @Inject(ServiceA)
    private readonly serviceA: ServiceA,
  ) {}

ServiceA is in ModuleA

@Module({
  providers: [ServiceA],
  exports: [ServiceA],
})
export class ModuleA {}

And I combine all of them in AppModule

@Module({
  imports: [ModuleA],
  providers: [ServiceB]
})
export class AppModule{}

THE QUESTION IS

I want to add a parameter in ServiceB's constructor

export class ServiceB {
  constructor(
    @Inject(ServiceA)
    private readonly serviceA: ServiceA,
    name: string
  ) {}

and I try to use useFactory() in AppModule to add that parameter

@Module({
  imports: [ModeulA],
  providers: [
  {
    provide: ServiceB,
    useFactory: () => new ServiceB(
      new ServiceA(),
      'JOHN'
    )
  }
  ]
})
export class AppModule{}

This cause generting a sencond ServiceA instance. How can I find the exsiting ServiceA instance and inject into ServiceB?

1 Answers

Read the docs Factory providers

Add ServiceA class to inject property and your factory function will receive the instance once called.

    {
    provide: ServiceB,
    useFactory: (srvA: ServiceA) => new ServiceB(
      srvA,
      'JOHN'
    ),
    inject: [ServiceA]
    }
Related