zx_wing
zx_wing

Reputation: 1966

Nestjs: inject provider into objects created by the key word new

I am trying to inject a provider to objects created by new. Is it possible? For example:

@Injectable()
export class SomeService {
}

export class SomeObject {

@Inject()
service: SomeService;
}

let obj = new SomeObject();

It's not working in my tests, the obj.service is undefined.

Upvotes: 2

Views: 2395

Answers (1)

Kim Kern
Kim Kern

Reputation: 60547

No, the dependency injection system will only work with objects that are created with it. You can create SomeObject as a custom provider though, e.g. with useClass:

@Injectable()
class SomeObject {
  constructor(private someService: SomeService) {}
}

@Module({
  providers: [
   SomeService,
   { provide: SomeObject, useClass: SomeObject },
  ],
})
export class ApplicationModule {}

or with useFactory for custom setup logic:

const someObjectFactory = {
  provide: 'SomeObject',
  useFactory: (someService: SomeService) => {
    // custom setup logic
    return new SomeObject(someService);
  },
  inject: [SomeService],
};

@Module({
  providers: [SomeService, connectionFactory],
})
export class ApplicationModule {}

Upvotes: 2

Related Questions