首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeDI @Inject()不起作用,但Container.get()起作用

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

Stack Overflow用户
提问于 2019-04-15 15:59:32
回答 1查看 6.1K关注 0票数 2

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

我尝试过用@Service()装饰类

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

我想知道这是否与以下事实有关,即我不是直接从node_modules而是从依赖项中使用typedi?

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

我的tsconfig.json:

代码语言:javascript
复制
"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/**/*"]
}

我想要注入的服务

代码语言:javascript
复制
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
  }
}

我要注入的服务

代码语言:javascript
复制
@Service()
export default class MyServiceName {
  public async someMethod(): SomeReturnType {
    return someReturnedData;
  }
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-15 19:07:14

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

这对我很有效:

代码语言:javascript
复制
// a.ts
import { Service } from "typedi";
@Service()
export class Foo {
  foo() {
    return 10;
  }
}
代码语言:javascript
复制
// b.ts
import { Foo } from "./a";
import { Inject } from "typedi";

export class Bar {
  @Inject() private readonly service: Foo
  foo() {
    console.log(this.service);
  }
}
代码语言:javascript
复制
// 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
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55684776

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档