是否可以仅使用 Nest.js 框架中的 DI 和 IoC 功能?如果是,如何实现?
我试图以这种方式实现它:
import { NestFactory } from "@nestjs/core";
import { Module, Injectable } from "@nestjs/common";
@Injectable()
class AppRepository {
sayHi() {
console.log("app repository");
console.log("Hello");
}
}
@Injectable()
class AppService {
constructor(private appRepository: AppRepository) {}
sayHi() {
console.log("app service");
this.appRepository.sayHi();
}
}
@Module({
imports: [],
providers: [AppService, AppRepository]
})
class AppModule {
constructor(private appService: AppService) {}
sayHi() {
console.log("app module");
this.appService.sayHi();
}
}
async function bootstrap() {
const app = await NestFactory.createApplicationContext(AppModule);
const module = app.get<AppModule>(AppModule);
module.sayHi();
}
bootstrap();
但是当我运行代码时,我得到:
app module
(node:70976) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'sayHi' of undefined
at AppModule.sayHi (/Users/jakub/projects/nest-di-clean/build/main.js:47:25)
at /Users/jakub/projects/nest-di-clean/build/main.js:60:16
at Generator.next (<anonymous>)
at fulfilled (/Users/jakub/projects/nest-di-clean/build/main.js:11:58)
at process._tickCallback (internal/process/next_tick.js:68:7)
at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
所以我得到了AppModule一个实例,但AppService没有注入一个实例。
我想在一个不需要控制器和其他服务器端东西的库中使用它。