Skip to content

API 概览

本页总结了公开的核心 API。准确的泛型定义请参阅软件包 README 和 TypeScript 声明文件。

Container

ts
import {
  Container,
  type ContainerOptions,
  type DependenciesMap,
  type Lazy,
  type LazySpec,
  type Module,
  type RegistrationKind,
  type Spec,
  type SpecMap,
} from '@inferdi/inferdi'
ts
class Container<T extends DependenciesMap = Record<never, never>> {
  constructor(options?: ContainerOptions)

  registerClass(key, Ctor, deps, kind?, lazyKey?)
  registerFactory(key, factory, kind?, lazyKey?)
  registerValue(key, value)
  override(key, value)
  use(fn)

  createScope()
  get(key)
  has(key)

  get disposed(): boolean
  dispose(): Promise<void>
  [Symbol.dispose](): void
  [Symbol.asyncDispose](): Promise<void>
}

注册方法

方法用途
registerClass注册一个构造函数及其依赖元组。
registerFactory注册自定义的构造逻辑。
registerValue注册一个由外部拥有的单例值。
override替换已有注册;若键已存在于本地缓存中则拒绝操作。
use应用一个模块构建器。

registerClassregisterFactory 接受 singletonscopedtransient 三种生命周期,以及可选的 lazyKey 伴随项。registerValue 始终为单例,且由外部拥有。

注册完成后,请将传给 registerClass 的依赖元组视为不可变。优化后的构造路径不会为它创建防御性副本。

override 的时机检查只查看当前容器的缓存。它能发现本地缓存的 singleton/scoped 值、registerValue 和重复覆盖,但不会记录 transient 解析,也不会记录通过子容器解析但由祖先容器拥有的值。请在解析依赖图之前应用覆盖。

命名空间类型

ts
namespace Container {
  type Resolve<C>
  type ResolveUnwrapped<C>
  type UnwrappedValue<C, K>
  type Providers<C>
}
类型用途
Container.Resolve<C>从已构建的容器中提取一个扁平的 { key: Value } 映射。
Container.ResolveUnwrapped<C>类似 Resolve,但只将受管理的 LazySpec 伴随项解包为 T;带有普通 .get() 方法的服务保持不变。
Container.UnwrappedValue<C, K>查询单个已解包的服务类型。
Container.Providers<C>为测试创建一组 provider thunk 的映射。

公开类型

ts
type Lazy<T> = { readonly get: () => T }
type RegistrationKind = 'singleton' | 'transient' | 'scoped'

interface ContainerOptions {
  readonly strict?: boolean
}

interface Spec<V, K extends RegistrationKind = 'singleton'> {
  readonly type: V
  readonly kind: K
}

type SpecMap<M, K extends RegistrationKind = 'singleton'> = {
  [P in keyof M]: Spec<M[P], K>
}

type Module<TIn extends DependenciesMap, TOut extends DependenciesMap> =
  (c: Container<TIn>) => Container<TIn & TOut>

适配器 API 形态

每个适配器都会导出:

  • 集成函数,例如 inferdiFastify
  • skipInferdiDispose
  • MaybePromise
  • 结构化的 InferdiScopeInferdiRootInferdiScopeOf 辅助类型
  • 框架专属的选项与上下文辅助类型

框架专属的泛型名称和生命周期细节请参阅各适配器页面。