首页 > web前端 > js教程 > 正文

TypeScript 中的 TSyringe 和依赖注入

Patricia Arquette
发布: 2024-09-25 19:21:42
原创
591 人浏览过

TSyringe and Dependency Injection in TypeScript

我不太喜欢像 NestJS 这样的大型框架;我一直喜欢以我想要的方式自由地构建我的软件,并以轻量级的方式决定结构。但在测试 NestJS 时我喜欢的是依赖注入。

依赖注入(DI)是一种设计模式,它允许我们通过消除创建和管理类依赖关系的责任来开发松散耦合的代码。这种模式对于编写可维护、可测试和可扩展的应用程序至关重要。在 TypeScript 生态系统中,TSyringe 作为一个强大且轻量级的依赖注入容器脱颖而出,它简化了这个过程。

TSyringe 是一个用于 TypeScript/JavaScript 应用程序的轻量级依赖注入容器。由 Microsoft 在其 GitHub (https://github.com/microsoft/tsyringe) 上维护,它使用装饰器进行构造函数注入。然后,它使用控制反转容器来存储基于令牌的依赖项,您可以用该令牌交换实例或值。

了解依赖注入

在深入了解 TSyringe 之前,我们先简要探讨一下什么是依赖注入以及它为何如此重要。

依赖注入是一种技术,对象从外部源接收其依赖项,而不是自己创建它们。这种方法有几个好处:

  1. 提高了可测试性:可以在单元测试中轻松模拟或存根依赖项。
  2. 增加模块化:组件更加独立,可以轻松替换或更新。
  3. 更好的代码可重用性:可以在应用程序的不同部分之间共享依赖关系。
  4. 增强的可维护性:依赖项的更改对依赖代码的影响最小。

设置 TSyringe

首先,让我们在您的 TypeScript 项目中设置 TSyringe:

npm install tsyringe reflect-metadata

登录后复制

在 tsconfig.json 中,确保有以下选项:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

登录后复制

在应用程序的入口点导入反射元数据:

import "reflect-metadata";

登录后复制

应用程序的入口点例如是 Next.js 13+ 上的根布局,也可以是小型 Express 应用程序中的主文件。

使用 TSyringe 实现依赖注入

我们以介绍中的示例为例,添加 TSyringe 糖:

让我们从适配器开始。

// @/adapters/userAdapter.ts
import { injectable } from "tsyringe"

@injectable()
class UserAdapter {
    constructor(...) {...}

    async fetchByUUID(uuid) {...}
}

登录后复制

注意到 @injectable() 装饰器了吗?是告诉TSyringe这个类可以在运行时注入。

所以我的服务正在使用我们刚刚创建的适配器。让我们将该适配器注入到我的服务中。

// @/core/user/user.service.ts
import { injectable, inject } from "tsyringe"
...

@injectable()
class UserService {
    constructor(@inject('UserAdapter') private readonly userAdapter: UserAdapter) {}

    async fetchByUUID(uuid: string) {
    ...
        const { data, error } = await this.userAdapter.fetchByUUID(uuid);
    ...
    }
}

登录后复制

这里我还使用了 @injectable 装饰器,因为 Service 将被注入到我的命令类中,但我还在构造函数参数中添加了 @inject 装饰器。此装饰器告诉 TSyringe 在运行时为 userAdapter 属性提供令牌 UserAdapter 的实例或值。

最后但并非最不重要的一点是,我的核心的根源:命令类(通常被错误地称为用例)。

// @/core/user/user.commands.ts
import { inject } from "tsyringe"
...

@injectable()
class UserCommands {
    constructor(@inject('UserService') private readonly userService: UserService) {}

    async fetchByUUID(uuid) {
    ...
        const { data, error } = this.userService.fetchByUUID(uuid);
    ...
    }
}

登录后复制

此时,我们已经告诉 TSyringe 将要注入什么以及要在构造函数中注入什么。但我们还没有制作容器来存储依赖项。我们可以通过两种方式做到这一点:

我们可以使用依赖注入注册表创建一个文件:

// @/core/user/user.dependencies.ts
import { container } from "tsyringe"
...

container.register("UserService", {useClass: UserService}) // associate the UserService with the token "UserService"
container.register("UserAdapter", {useClass: UserAdapter}) // associate the UserAdapter with the token "UserAdapter"

export { container }

登录后复制

但是我们也可以使用@registry装饰器。

// @/core/user/user.commands.ts
import { inject, registry, injectable } from "tsyringe"
...

@injectable()
@registry([
    {
        token: 'UserService',
        useClass: UserService
    },
    {
        token: 'UserAdapter',
        useClass: UserAdapter
    },
])
export class UserCommands {
    constructor(@inject('UserService') private readonly userService: UserService) {}

    async fetchByUUID(uuid) {
    ...
        const { data, error } = this.userService.fetchByUUID(uuid);
    ...
    }
}

container.register("UserCommands", { useClass: UserCommands})

export { container }

登录后复制

两种方法各有利弊,但归根结底,这只是个人喜好的问题。

现在我们的容器已经充满了我们的依赖项,我们可以根据需要使用容器的resolve方法从容器中获取它们。

import { container, UserCommands } from "@/core/user/user.commands"

...
const userCommands = container.resolve<UserCommands>("UserCommands")
await userCommands.fetchByUUID(uuid)
...

登录后复制

这个例子非常简单,因为每个类只依赖于另一个类,但我们的服务可能依赖于许多类,依赖注入确实有助于保持一切整洁。

但是等等!别就这样离开我!测试怎么样?

使用 TSyringe 进行测试

我们的注入还可以通过将模拟对象直接发送到我们的依赖项中来帮助我们测试代码。让我们看一个代码示例:

import { container, UserCommands } from "@/core/user/user.commands"

describe("test ftw", () => {
    let userAdapterMock: UserAdapterMock
    let userCommands: UserCommands

    beforeEach(() => {
        userAdapterMock = new UserAdapter()
        container.registerInstance<UserAdapter>("UserAdapter", userAdapter)
        userCommands = container.resolve<UserCommands>("UserCommands")
    });

    ...
});

登录后复制

现在 UserAdapter 令牌包含一个模拟,它将被注入到依赖类中。

最佳实践和技巧

  1. 使用接口:为您的依赖项定义接口,使它们可以轻松交换和测试。为了简单起见,我在本文中没有使用接口,但接口就是生命。
  2. 避免循环依赖:构建代码以避免循环依赖,这可能会导致 TSyringe 出现问题。
  3. 使用标记进行命名:不要使用字符串文字作为注入标记,而是创建常量标记:

    export const USER_REPOSITORY_TOKEN = Symbol("UserRepository");
    
    
    登录后复制
  4. Scoped containers: Use scoped containers for request-scoped dependencies in web applications.

  5. Don't overuse DI: Not everything needs to be injected. Use DI for cross-cutting concerns and configurable dependencies.

If you've come this far, I want to say thank you for reading. I hope you found this article instructive. Remember to always consider the specific needs of your project when implementing dependency injection and architectural patterns.

Likes and comment feedback are the best ways to improve.

Happy coding!

以上是TypeScript 中的 TSyringe 和依赖注入的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!