@gitlab/needle 文档
@gitlab/needle 是TypeScript的轻量级依赖性注射框架,使用ES 第3级装饰. 它为管理您 TypeScript 项目中的依赖性提供了一个类型安全解决方案 .
主要特点
- 执行新的ES阶段3的装饰器标准(TS实验装饰器现在是 标为遗产 和尽管仍然支持, 建议使用标准前进)
- 兼容最新的类型脚本和新建而无需特殊构建旗帜
- 完全类型安全,确保正确的依赖类型和构造参数
基本用途
定义接口
interface A {
field: string;
}
interface B {
hello(): string;
}
创建接口 ID
import { createInterfaceId } from '@gitlab/needle';
const A = createInterfaceId<A>('A');
const B = createInterfaceId<B>('B');
执行和装饰类
@gitlab/needle 为定义可以在容器中注册的服务提供多个装饰选项.
@ 图像
这个 @Implements 类工具的接口 .
import { Implements } from '@gitlab/needle';
@Implements(A)
class AImpl implements A {}
@ Service (英语)
这个 @Service 装饰者定义了一种服务,是系统要求创建一种服务描述符. 我们可以在这个装饰器中指定依赖性和寿命.
import { Service, ServiceLifetime } from '@gitlab/needle';
@Service({
dependencies: [B, C],
lifetime: ServiceLifetime.Singleton,
autoActivate: false
})
class AImpl implements A {
constructor(b: B, c: C) {}
}
这个 lifetime 参数可以是:
ServiceLifetime.Singleton- 这项服务是一次性创建的,并适用于所有请求.ServiceLifetime.Transient- 在每次请求服务时,都创建新的服务实例.ServiceLifetime.Scoped- 为每个范围建立一个新的实例
这个 autoActivate 参数控制当容器出现时是否应当自动解决服务
已经建成。 这对于作为切入点的服务来说是有用的,例如,初始化了一个websocket收听器.
@ 内插
这个 @Injectable 装饰器是一种方便的装饰器,结合了 @Implements 财务报告和审定财务报表 @Service默认情况下,它宣布服务寿命为 Singleton
import { Injectable } from '@gitlab/needle';
@Injectable(A, [])
class AImpl implements A {
field = 'value';
}
@Injectable(B, [A])
class BImpl implements B {
#a: A;
constructor(a: A) {
this.#a = a;
}
hello() {
return `B.hello says A.field = ${this.#a.field}`;
}
}
登记事务 ServiceCollection
目的
ServiceCollection 负责:
- 登记服务及其依赖性
- 验证服务登记
- 建设a
ServiceProvider能够解决这些服务
使用量
创建服务库
import { ServiceCollection } from '@gitlab/needle';
const services = new ServiceCollection();
登记事务
ServiceCollection 提供几种登记服务的方式:
方法1:添加装饰有: @Service 或者说 @Injectable
import { ServiceCollection, Injectable, createInterfaceId } from '@gitlab/needle';
// Define interface and ID
interface Logger {
log(message: string): void;
}
const Logger = createInterfaceId<Logger>('Logger');
// Implement and decorate class
@Injectable(Logger, [])
class ConsoleLogger implements Logger {
log(message: string) {
console.log(message);
}
}
// Register with ServiceCollection
const services = new ServiceCollection();
services.addClass(ConsoleLogger);
方法2:直接添加服务说明
对于更先进的情景,您可以创建并添加服务描述符:
import {
createInstanceDescriptor,
createConstructorDescriptor,
ServiceLifetime
} from '@gitlab/needle';
// Add an existing instance
const config = new ConfigurationService();
services.add(
createInstanceDescriptor({
instance: config,
aliases: [Configuration]
})
);
// Add a constructor-based service
services.add(
createConstructorDescriptor({
implementation: DatabaseService,
aliases: [Database],
dependencies: [Configuration],
lifetime: ServiceLifetime.Scoped,
autoActivate: false
})
);
连锁登记
登记方法返回服务收集实例以支持方法链:
services
.addClass(UserService)
.addClass(AuthenticationService)
.add(
createInstanceDescriptor({
instance: new ConfigurationService(),
aliases: [Configuration],
}),
);
验证 ServiceCollection
在建立服务供应商之前,您可以验证服务注册,以确保没有问题:
const validationResult = services.validate();
if (!validationResult.isValid) {
console.error('Service validation failed:');
validationResult.errors.forEach((error) => console.error(error.message));
}
核实:
- 缺少依赖关系
- 循环依赖关系
- 需要单一执行的多重执行服务
建设a ServiceProvider
登记所有服务后,您可以建立服务服务公司开始解析服务:
// This will validate services and throw an error if validation fails
const serviceProvider = services.build();
如果你准备好了 autoActivate: true 对于任何服务,当提供者建成时,它们将被自动即时处理.
ServiceProvider
目的
ServiceProvider 负责:
- 根据已注册的服务描述符解决服务标识符
- 管理服务寿命(锡金、瞬态、范围)
- 解决服务之间的依赖性
使用 ServiceProvider
获取服务
为了获得单一服务:
const logger = serviceProvider.getRequiredService(Logger);
logger.log('Hello, world!');
这种方法将:
- 掷出
ServiceNotRegisteredError如果未登记执行 - 掷出
AmbiguousMatchError如果登记了多个执行
为接口获取全部服务
为获得一项服务的所有注册实施:
const loggers = serviceProvider.getServices(Logger);
loggers.forEach((logger) => logger.log('Hello from all loggers'));
如果没有为接口注册服务,此方法不会扔出并返回空阵列 .
管理服务范围
理解服务
服务行为取决于其注册寿命:
- 单子: 整个应用周期的一个实例
- 范围d: 每个范围一个实例
- 短暂: 每次请求服务时新建实例
创建和使用范围
操作程序为标有下列标记的服务提供隔离: ServiceLifetime.Scoped它们可用于请求范围服务或隔离服务,其寿命不同于应用寿命.
// Root provider from ServiceCollection
const rootProvider = services.build();
// Create a scope
const scope = rootProvider.createScope();
try {
// Get a scoped service within this scope
const userService = scope.getRequiredService(UserService);
// Use the service...
await userService.processRequest();
} finally {
// Always dispose the scope when finished to prevent memory leaks
scope.dispose();
}
嵌入范围
您可以创建嵌入式瞄准镜, 在服务分辨率中建立等级:
const rootProvider = services.build();
const parentScope = rootProvider.createScope();
try {
// Create a child scope
const childScope = parentScope.createScope();
try {
// Use services from the child scope
const service = childScope.getRequiredService(ScopedService);
// ...
} finally {
childScope.dispose();
}
} finally {
parentScope.dispose();
}
资源处置
正确处置范围对于防止内存泄漏十分重要,特别是对于实施范围服务 Disposable 接口 :
interface Disposable {
dispose(): void;
}
@Implements(DataService)
@Service({
dependencies: [],
lifetime: ServiceLifetime.Scoped
})
class DatabaseConnection implements DataService, Disposable {
#connection: Connection;
constructor() {
this.#connection = createConnection();
}
// Methods...
dispose() {
// Clean up resources when the scope is disposed
this.#connection.close();
}
}
// Usage
const scope = rootProvider.createScope();
try {
const db = scope.getRequiredService(DataService);
// Use database...
} finally {
// This will call dispose() on all scoped services in this scope
scope.dispose();
}
初始化容器
import { Container } from '@gitlab/needle';
const container = new Container();
container.instantiate(AImpl, BImpl);
获取依赖关系(如有需要)(DEPECATED)
const b = container.get(B);
console.log(b.hello());
高级用途
添加外部依赖
对于无法由容器提供的依赖性,您需要手动添加. 以下是增加外部日志依赖性的例子:
import { createInterfaceId, brandInstance } from '@gitlab/needle';
interface Logger {
log(...args: unknown[]): void;
}
const Logger = createInterfaceId<Logger>('Logger');
const customLogger: Logger = {
log: (...args) => console.log('custom logger', ...args),
};
container.addInstances(brandInstance(Logger, customLogger));
示例
我们必须在容器上添加语言服务器连接(我们从已经创建的VS代码框架中获得). 为此,我们 创建异名 联 合 国 Connection 调用 LsConnection (这样我们就能创建 InterfaceId和 把它加进容器里。 。 。 .
收款
当您需要输入特定接口的所有已注册实例时,您可以使用收藏依赖:
import { createInterfaceId, collection } from '@gitlab/needle';
// Define interface and create its ID
interface Plugin {
execute(): void;
}
const Plugin = createInterfaceId<Plugin>('Plugin');
// Implement multiple plugins
@Injectable(Plugin, [])
class Plugin1 implements Plugin {
execute() {
console.log('Plugin 1');
}
}
@Injectable(Plugin, [])
class Plugin2 implements Plugin {
execute() {
console.log('Plugin 2');
}
}
// Inject all plugins into a manager
@Injectable(PluginManager, [collection(Plugin)])
class PluginManager {
constructor(private plugins: Plugin[]) {}
executeAll() {
this.plugins.forEach((p) => p.execute());
}
}
// Initialize
const container = new Container();
container.instantiate(Plugin1, Plugin2, PluginManager);
// Use
const manager = container.get(PluginManager);
manager.executeAll(); // Outputs: "Plugin 1" "Plugin 2"
如果在多处需要相同的收藏,可以创建一个收藏Id变量:
import { createInterfaceId, createCollectionId } from '@gitlab/needle';
// Same Plugin setup as example above
const PluginsCollection = createCollectionId(Plugin);
@Injectable(PluginManager1, [PluginsCollection])
class PluginManager1 {
constructor(private plugins: Plugin[]) {}
}
@Injectable(PluginManager2, [PluginsCollection])
class PluginManager2 {
constructor(private plugins: Plugin[]) {}
}
API 参考
createInterfaceId<T>(id: string): InterfaceId<T>
为接口创建独有的运行时间标识符.
createCollectionId<T>(interfaceId: InterfaceId<T>): CollectionId<T>
为收集接口创建运行时间标识符.
collection<T>(interfaceId: InterfaceId<T>): CollectionId<T>
别名 createCollectionId,在不需要中间变量时,打算直接用于 @ Injectable.
@Injectable(id: InterfaceId<I>, dependencies: (InterfaceId<unknown> | CollectionId<unknown>)[])
类的装饰符,以标记为可注入并指定其依赖性.
Container
instantiate(...classes: Class[]): void:初始化指定的类别.addInstances(...instances: BrandedInstance<object>[]): void: 在容器中添加已初始化的物体.get<T>(id: InterfaceId<T>): T:从容器取出一个实例.
brandInstance<T>(id: InterfaceId<T>, instance: T): BrandedInstance<T>
用于 container.addInstances()。 。 。 .
最佳做法
- 为您的依赖定义接口 .
- 使用
createInterfaceId每个接口. - 执行课程并装饰
@Injectable。 。 。 . - 在应用程序的入口处初始化您的容器 .
- 使用
container.get()慢慢地,更喜欢建筑师注射.
代码中的实例
ConfigService(无构造参数)ConnectionService(许多构造者论证)- 证明阶级
解决问题
- 确保所有课程的装饰
@Injectable。 。 。 . - 保证您
InterfaceId实例有正确的界面类型和字符串标识符. - 确保所有构造符参数执行其中提及的接口
@Injectable装饰师.
VS 代码片断
为了减少锅炉板,考虑在您的 VS 代码中添加此片段 TypeScript 片段 :
{
"New DI Class": {
"prefix": "diclass",
"body": [
"import { Injectable, createInterfaceId } from '@gitlab/needle';",
"",
"export interface ${1:InterfaceName} {}",
"",
"export const ${1:InterfaceName} = createInterfaceId<${1:InterfaceName}>('${1:InterfaceName}');",
"",
"@Injectable(${1:InterfaceName}, [])",
"export class Default${1:InterfaceName} implements ${1:InterfaceName} {}"
],
"description": "Creates DI framework boilerplate"
}
}
财务问题
你为什么不装饰 构造器参数?
你不能,因为ES阶段3的装饰不支持装饰方法/功能参数.
如何执行?
- 类型定义
@Injectable是一种黑暗的,只写类型的魔法 - 页:1
Container执行是一个直截了当的图形转录和字符串验证
在下一节提到的博客文章中.
兼容性
目前的实施既适用于遗留的实验装饰,也适用于新的TypeScript 5装饰.
如果装饰器在遗留的环境中使用,你就不会有错误解释你应该只使用 Implements 财务报告和审定财务报表 Service 课上装饰.