💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
TypeDI是一个TypeScript和JavaScript的依赖注入库。 ***** ## 安装 > 注意:这个安装指南是针对TypeScript的使用,如果你想使用TypeDI而不使用Typescript,请阅读JavaScript的入门指南。 要开始使用TypeDI,请通过NPM安装所需的包。 ``` npm install typedi reflect-metadata ``` 在你的应用程序的第一行导入`reflect-metadata`包。 ``` import 'reflect-metadata'; // 在你导入reflect-metadata包之后 // 再接着你的其他导入和初始化代码! ``` 作为最后一步,你需要在你的Typescript配置中启用发射装饰器元数据( emitting decorator metadata)。在你的`tsconfig.json`文件中的`compilerOptions`键下添加这两行。 ``` "emitDecoratorMetadata": true, "experimentalDecorators": true, ``` 现在你已经准备好使用TypeDI与Typescript了 ! ***** ## 基本用法 最基本的用法是请求一个类定义的实例。TypeDI将检查该类的实例是否已经被创建并返回缓存的版本,或者它将创建一个新的实例,缓存并返回它。 ``` import { Container, Service } from 'typedi'; @Service() class ExampleInjectedService { printMessage() { console.log('I am alive!'); } } @Service() class ExampleService { constructor( // 因为我们用@Service()装饰器注解了ExampleInjectedService // 当从TypeDI请求ExampleService类时 // TypeDI将自动在这里注入一个ExampleInjectedService的实例。 public injectedService: ExampleInjectedService ) {} } const serviceInstance = Container.get(ExampleService); // 我们从TypeDI请求一个ExampleService的实例 serviceInstance.injectedService.printMessage(); // 在console打印"I am alive!" ```