TypeDI @Inject()不起作用,但是Container.get()起作用

时间:2019-04-15 07:59:32

标签: node.js typescript

我面临着奇怪的问题, Container.get(MyServiceName);返回所需的服务,但是用@Inject()装饰的类属性未定义。

我尝试用@Service()装饰类

我确实在应用程序的入口点导入了反射元数据 导入“ reflect-metadata”;

我想知道是否可能与事实有关,我不是直接从我的node_modules中而是从我的依赖中使用typedi?

应用程序既不使用Express框架,也不使用路由控制器

我的tsconfig.json:

"compilerOptions": {

    "declaration": true,
    "pretty": true,
    "esModuleInterop": true,
    "target": "esnext",
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noUnusedLocals": false,
    "moduleResolution": "node",
    "noUnusedParameters": true,
    "strictPropertyInitialization": false,
    "module": "commonjs",
    "lib": ["dom", "es2018"],
    "importHelpers": true,
    "outDir": "./dist",
    "strict": true,
    "typeRoots": ["node_modules/@types"],
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "sourceMap": true
  },
  "include": ["./src/**/*"],
  "exclude": ["node_modules", "./dist/**/*"]
}

我想注入的服务

import MyServiceName from '../services/MyServiceName';
import { Container, Inject, Service } from 'my_dependency/lib';

export default class SomeClass{
  @Inject()
  private readonly someService: MyServiceName;

  public async someMethod(): SomeResponseType {
    const thatWorks = Container.get<MyServiceName>(MyServiceName);
    console.log(this.someService); // undefined
    console.log(thatWorks); // proper class
  }
}

我要注入的服务

@Service()
export default class MyServiceName {
  public async someMethod(): SomeReturnType {
    return someReturnedData;
  }
}

我想通过@Inject()装饰器注入依赖项

1 个答案:

答案 0 :(得分:0)

您需要使用SomeClass创建Container#get的实例,否则容器将无法注入该属性。

这对我有用:

// a.ts
import { Service } from "typedi";
@Service()
export class Foo {
  foo() {
    return 10;
  }
}
// b.ts
import { Foo } from "./a";
import { Inject } from "typedi";

export class Bar {
  @Inject() private readonly service: Foo
  foo() {
    console.log(this.service);
  }
}
// test.ts
import "reflect-metadata";
import { Bar } from "./b";
import { Container } from "typedi";

const noFoo = new Bar();
noFoo.foo(); // yields undefined

const withFoo = Container.get<Bar>(Bar);
withFoo.foo(); // yields Foo