簡體   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