You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeGraphQL中结合tsyringe实现依赖注入?

可以用tsyringe为TypeGraphQL实现依赖注入

完全没问题,TypeGraphQL支持自定义依赖注入容器,所以能轻松集成tsyringe。下面是具体实现步骤和代码示例:

1. 安装所需依赖

确保已安装核心依赖:

npm install tsyringe reflect-metadata type-graphql graphql apollo-server-express express
# 或使用yarn
yarn add tsyringe reflect-metadata type-graphql graphql apollo-server-express express

2. 启用反射元数据

在项目入口文件(如index.ts)顶部导入并启用reflect-metadata——这是tsyringe和TypeGraphQL实现依赖注入的基础:

import "reflect-metadata";

3. 实现TypeGraphQL容器适配器

TypeGraphQL需要符合ContainerInterface的容器实例,我们可以写一个适配器类,将tsyringe的容器逻辑适配进去:

import { ContainerInterface } from "type-graphql";
import { container as tsyringeContainer } from "tsyringe";

export class TsyringeContainerAdapter implements ContainerInterface {
  get<T>(target: { new (...args: any[]): T }): T {
    return tsyringeContainer.resolve(target);
  }
}

4. 注册可注入服务

用tsyringe的@injectable()装饰器标记服务类,确保容器可以解析它们:

import { injectable } from "tsyringe";

@injectable()
export class UserService {
  async getUsers() {
    // 这里编写业务逻辑,比如从数据库获取用户数据
    return [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }];
  }
}

如果需要指定单例生命周期,可在入口文件中注册:

import { container } from "tsyringe";
import { UserService } from "./services/UserService";

container.registerSingleton(UserService);

5. 在Resolver中注入服务

在TypeGraphQL的Resolver类里,直接通过构造函数声明依赖——自定义容器会自动从tsyringe容器中解析并注入实例:

import { Resolver, Query, ObjectType, Field, Int } from "type-graphql";
import { UserService } from "../services/UserService";

// 定义GraphQL对象类型
@ObjectType()
class User {
  @Field(() => Int)
  id: number;

  @Field()
  name: string;
}

// Resolver类
@Resolver()
export class UserResolver {
  // 构造函数注入UserService
  constructor(private readonly userService: UserService) {}

  @Query(() => [User])
  async users() {
    return this.userService.getUsers();
  }
}

6. 构建Schema并启动服务器

最后,在启动服务器时,告诉TypeGraphQL使用我们的tsyringe容器适配器:

import { buildSchema } from "type-graphql";
import { ApolloServer } from "apollo-server-express";
import express from "express";
import { TsyringeContainerAdapter } from "./TsyringeContainerAdapter";
import { UserResolver } from "./resolvers/UserResolver";

async function startServer() {
  const app = express();

  // 构建TypeGraphQL Schema,指定自定义容器
  const schema = await buildSchema({
    resolvers: [UserResolver],
    container: new TsyringeContainerAdapter(),
  });

  // 创建并启动Apollo Server
  const apolloServer = new ApolloServer({ schema });
  await apolloServer.start();
  apolloServer.applyMiddleware({ app });

  app.listen(4000, () => {
    console.log("GraphQL API running at http://localhost:4000/graphql");
  });
}

startServer();

这样就完成了tsyringe与TypeGraphQL的集成,Resolver中的服务会被tsyringe自动注入,你可以直接复用现有项目中已注册的tsyringe服务。

内容的提问来源于stack exchange,提问作者Leandro Santiago Gomes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 03:05:12