Tsyringe使用register带依赖时resolve抛出TypeInfo未知错误
Tsyringe: 为何
register/registerSingleton无法解析带构造依赖的类? 核心原因
Tsyringe对构造参数的类型解析完全依赖Reflect元数据,但register/registerSingleton方法不会自动为类注入这类元数据。只有@injectable()(包括基于它实现的@singleton()等装饰器)会在编译阶段通过typeInfo.set(target, getParamInfo(target))存储类的构造参数信息——这是框架的机制限制,并非你的操作错误。
测试场景拆解
- 测试1/4正常运行:测试1用
@singleton()装饰器自动注入了元数据;测试4的Parent无构造依赖,容器无需解析参数,因此register能正常工作。 - 测试2/3报错:你用
registerSingleton/register注册带构造依赖的Parent类,但未给Parent及其依赖类添加@injectable()或@singleton()装饰器,容器无法获取构造参数的类型信息,因此抛出「TypeInfo not known for "Parent"」错误。
正确解决方式
无论使用哪种注册方法,带构造依赖的类必须添加@injectable()装饰器(@singleton()是@injectable()+单例生命周期的语法糖),以下是修正后的示例:
修正测试2代码
import { container, injectable } from 'tsyringe'; @injectable() class Child1 {} @injectable() class Child2 {} @injectable() class Parent { constructor(public readonly child1: Child1, public readonly child2: Child2) {} } container.registerSingleton(Child1); container.registerSingleton(Child2); container.registerSingleton(Parent); const parent = container.resolve(Parent); expect(parent).toBeInstanceOf(Parent); expect(parent.child1).toBe(container.resolve(Child1)); expect(parent.child2).toBe(container.resolve(Child2));
结合装饰器与register自定义生命周期
如果需要通过register指定生命周期,同样需先给类添加装饰器:
import { container, injectable, Lifecycle } from 'tsyringe'; @injectable() class Child1 {} @injectable() class Child2 {} @injectable() class Parent { constructor(public readonly child1: Child1, public readonly child2: Child2) {} } container.register(Child1, { useClass: Child1 }, { lifecycle: Lifecycle.Singleton }); container.register(Child2, { useClass: Child2 }, { lifecycle: Lifecycle.Singleton }); container.register(Parent, { useClass: Parent }, { lifecycle: Lifecycle.Singleton }); const parent = container.resolve(Parent);
关键总结
- 无构造依赖的类:可直接用
register/registerSingleton注册 - 带构造依赖的类:必须先添加
@injectable()(或@singleton()等装饰器),再使用任意注册方式
内容的提问来源于stack exchange,提问作者Mehmet Ataş
相关产品推荐
相关产品推荐

