I have two problems using nestJs DI (and unfortunately the documentations are all the same and contains only basic usage information about the topics):
- what if I construct an AppModule, and simple I need to create a service just in case (currently my rabbitMq handler - served in moleculer - needs a document service instance)
- what if the document service instance (for rabbitMq) depends on a user instance, which is a dependency for the document service, and in this case the user must be created (injected) in a different way than as usual (when it is used for serving a web request)?
@Injectable()
class DocumentService {
@Inject('USER') user: IUser;
@Inject() protected userRepository: UserRepository;
@Inject() protected documentRepository: DocumentRepository;
public void saveDocument() {
...
}
}
where
@Module({
controllers: [DocumentController]
providers: [
// repositories
UserRepository, DocumentRepository,
// services
DocumentService,
// user
{
provide: 'USER',
scope: Scope.REQUEST,
useFactory: (req:Request) => req["user"] ?? null,
},
],
exports: ['USER'],
})
export class AppModule {}
What I should use is a code like this:
let rabbitMqUser = new user('rabbitMqServiceUser');
// change the IUser not come from request but use this instance for now:
// but use the DI injections describe above for the 'default' web request case
let documentService = pleaseNestJsConstructForMe<DocumentService>(where 'USER'=rabbitMqUser);