繁体   English   中英

如何仅使用来自 Nest.js 框架的依赖注入容器?

[英]How to use only dependency injection container from Nest.js framework?

是否可以仅使用 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的实例。

我想在我贡献的库中使用它,该库不需要控制器和其他服务器端的东西。

我找到了解决方案。 我没有使用nest-cli创建一个新项目,而是使用 TypeScript 创建了一个空的 npm 项目,并添加了@nestjs/common@nestjs/core作为依赖项(我想最小化依赖项)。 我的错误是在tsconfig.json文件中,我忘记允许emitDecoratorMetadata 这是我的package.jsontsconfig.json文件,供有兴趣的人使用:

package.json

{
  "name": "nest-di-clean",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "compile": "yarn tsc",
    "start": "node ./build/main.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@nestjs/common": "^6.11.5",
    "@nestjs/core": "^6.11.5",
    "reflect-metadata": "^0.1.13",
    "rxjs": "^6.5.4"
  },
  "devDependencies": {
    "@types/node": "^13.7.0",
    "typescript": "^3.7.5"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2015",                     
    "module": "commonjs",                   
    "outDir": "./build",                    
    "strict": true,                         
    "esModuleInterop": true,                
    "experimentalDecorators": true,         
    "emitDecoratorMetadata": true,          
    "forceConsistentCasingInFileNames": true
  }
}

main.js文件的内容都在我的问题中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM