# @gitlab/needle 中文文档

规范地址：https://npmcn.com/package/%40gitlab/needle/

版本：2\.0\.0
npm 元数据更新时间：2026-11-04T18:04:56.491Z
中文译文更新时间：2026-11-16T11:03:46.263Z
软件包许可：未声明

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40gitlab/needle
原文对照：https://npmcn.com/package/%40gitlab/needle/?lang=original

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：265 kB，9 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- 首次发布：2025-02-06T16:31:37.172Z
- 最新版本发布：2026-02-16T18:00:37.900Z
- 近 30 天下载量：26359（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：10（近 12 个月 1 个）

## 中文简介

`@gitlab/needle` 是TypeScript的轻量级依赖性注射框架,使用ES 第3级装饰. 它为管理您 TypeScript 项目中的依赖性提供了一个类型安全解决方案 .

## 安装

```sh
npm install @gitlab/needle
```

也可以使用：`pnpm add @gitlab/needle`、`yarn add @gitlab/needle`、`bun add @gitlab/needle`

## README

# `@gitlab/needle` 文档

`@gitlab/needle` 是TypeScript的轻量级依赖性注射框架,使用ES 第3级装饰. 它为管理您 TypeScript 项目中的依赖性提供了一个类型安全解决方案 .

## 主要特点

-   执行新的ES阶段3的装饰器标准(TS实验装饰器现在是 [标为遗产](https://devblogs.microsoft.com/typescript/announcing-typescript-5-0/#differences-with-experimental-legacy-decorators) 和尽管仍然支持, 建议使用标准前进)
-   兼容最新的类型脚本和新建而无需特殊构建旗帜
-   完全类型安全,确保正确的依赖类型和构造参数

## 基本用途

1.  [定义接口](https://npmcn.com/package/%40gitlab/needle/#readme-define-interfaces)
2.  [创建接口 ID](https://npmcn.com/package/%40gitlab/needle/#readme-create-interface-ids)
3.  [执行和装饰类](https://npmcn.com/package/%40gitlab/needle/#readme-implement-and-decorate-classes)
4.  [登记服务处](https://npmcn.com/package/%40gitlab/needle/#readme-register-services-with-servicecollection)
5.  [与服务机构合作](https://npmcn.com/package/%40gitlab/needle/#readme-serviceprovider)
6.  [管理服务范围](https://npmcn.com/package/%40gitlab/needle/#readme-managing-service-scopes)
7.  [初始化容器](https://npmcn.com/package/%40gitlab/needle/#readme-initialize-container-deprecated)
8.  [获取依赖关系(如有需要)(DEPECATED)](https://npmcn.com/package/%40gitlab/needle/#readme-retrieve-dependencies-if-needed-deprecated)

### 定义接口

```typescript
interface A {
  field: string;
}

interface B {
  hello(): string;
}
```

### 创建接口 ID

```typescript
import { createInterfaceId } from '@gitlab/needle';

const A = createInterfaceId<A>('A');
const B = createInterfaceId<B>('B');
```

### 执行和装饰类

`@gitlab/needle` 为定义可以在容器中注册的服务提供多个装饰选项.

#### @ 图像

这个 `@Implements` 类工具的接口 .

```typescript
import { Implements } from '@gitlab/needle';

@Implements(A)
class AImpl implements A {}
```

#### @ Service (英语)

这个 `@Service` 装饰者定义了一种服务,是系统要求创建一种服务描述符. 我们可以在这个装饰器中指定依赖性和寿命.

```typescript
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`

```typescript
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` 能够解决这些服务

#### 使用量

##### 创建服务库

```typescript
import { ServiceCollection } from '@gitlab/needle';

const services = new ServiceCollection();
```

##### 登记事务

`ServiceCollection` 提供几种登记服务的方式:

###### 方法1:添加装饰有: `@Service` 或者说 `@Injectable`

```typescript
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:直接添加服务说明

对于更先进的情景,您可以创建并添加服务描述符:

```typescript
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
  })
);
```

##### 连锁登记

登记方法返回服务收集实例以支持方法链:

```typescript
services
  .addClass(UserService)
  .addClass(AuthenticationService)
  .add(
    createInstanceDescriptor({
      instance: new ConfigurationService(),
      aliases: [Configuration],
    }),
  );
```

#### 验证 `ServiceCollection`

在建立服务供应商之前,您可以验证服务注册,以确保没有问题:

```typescript
const validationResult = services.validate();

if (!validationResult.isValid) {
  console.error('Service validation failed:');
  validationResult.errors.forEach((error) => console.error(error.message));
}
```

核实:

-   缺少依赖关系
-   循环依赖关系
-   需要单一执行的多重执行服务

#### 建设a `ServiceProvider`

登记所有服务后,您可以建立服务服务公司开始解析服务:

```typescript
// This will validate services and throw an error if validation fails
const serviceProvider = services.build();
```

如果你准备好了 `autoActivate: true` 对于任何服务,当提供者建成时,它们将被自动即时处理.

### `ServiceProvider`

#### 目的

`ServiceProvider` 负责:

-   根据已注册的服务描述符解决服务标识符
-   管理服务寿命(锡金、瞬态、范围)
-   解决服务之间的依赖性

#### 使用 `ServiceProvider`

##### 获取服务

为了获得单一服务:

```typescript
const logger = serviceProvider.getRequiredService(Logger);
logger.log('Hello, world!');
```

这种方法将:

-   掷出 `ServiceNotRegisteredError` 如果未登记执行
-   掷出 `AmbiguousMatchError` 如果登记了多个执行

##### 为接口获取全部服务

为获得一项服务的所有注册实施:

```typescript
const loggers = serviceProvider.getServices(Logger);
loggers.forEach((logger) => logger.log('Hello from all loggers'));
```

如果没有为接口注册服务,此方法不会扔出并返回空阵列 .

### 管理服务范围

#### 理解服务

服务行为取决于其注册寿命:

-   **单子**: 整个应用周期的一个实例
-   **范围d**: 每个范围一个实例
-   **短暂**: 每次请求服务时新建实例

#### 创建和使用范围

操作程序为标有下列标记的服务提供隔离: `ServiceLifetime.Scoped`它们可用于请求范围服务或隔离服务,其寿命不同于应用寿命.

```typescript
// 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();
}
```

##### 嵌入范围

您可以创建嵌入式瞄准镜, 在服务分辨率中建立等级:

```typescript
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` 接口 :

```typescript
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();
}
```

### 初始化容器

```typescript
import { Container } from '@gitlab/needle';

const container = new Container();
container.instantiate(AImpl, BImpl);
```

### 获取依赖关系(如有需要)(DEPECATED)

```typescript
const b = container.get(B);
console.log(b.hello());
```

## 高级用途

### 添加外部依赖

对于无法由容器提供的依赖性,您需要手动添加. 以下是增加外部日志依赖性的例子:

```typescript
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代码框架中获得). 为此,我们 [创建异名](https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/blob/91232887debe11b2b8830975c1d9f8748b85707b/src/common/external_interfaces.ts#L5) 联 合 国 `Connection` 调用 `LsConnection` (这样我们就能创建 `InterfaceId`和 [把它加进容器里](https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/blob/91232887debe11b2b8830975c1d9f8748b85707b/src/node/main.ts#L101)。 。 。 .

### 收款

当您需要输入特定接口的所有已注册实例时,您可以使用收藏依赖:

```typescript
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变量:

```typescript
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()`。 。 。 .

## 最佳做法

1.  为您的依赖定义接口 .
2.  使用 `createInterfaceId` 每个接口.
3.  执行课程并装饰 `@Injectable`。 。 。 .
4.  在应用程序的入口处初始化您的容器 .
5.  使用 `container.get()` 慢慢地,更喜欢建筑师注射.

## 代码中的实例

-   [`ConfigService`](https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/blob/91232887debe11b2b8830975c1d9f8748b85707b/src/common/config_service.ts#L110) (无构造参数)
-   [`ConnectionService`](https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/blob/91232887debe11b2b8830975c1d9f8748b85707b/src/common/connection_service.ts#L50) (许多构造者论证)
-   [证明阶级](https://gitlab.com/gitlab-org/editor-extensions/gitlab-lsp/blob/91232887debe11b2b8830975c1d9f8748b85707b/src/node/main.ts#L125)

## 解决问题

-   确保所有课程的装饰 `@Injectable`。 。 。 .
-   保证您 `InterfaceId` 实例有正确的界面类型和字符串标识符.
-   确保所有构造符参数执行其中提及的接口 `@Injectable` 装饰师.

## VS 代码片断

为了减少锅炉板,考虑在您的 VS 代码中添加此片段 TypeScript 片段 :

```json
{
  "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的装饰不支持装饰方法/功能参数.

-   [见第1阶段关于参数装饰器的建议](https://docs.google.com/document/d/1Qpkqf_8NzAwfD8LdnqPjXAQ2wwh8BBUGynhn-ZlCWT0/edit#heading=h.t9k9f05noi8w)

### 如何执行?

-   类型定义 `@Injectable` 是一种黑暗的,只写类型的魔法
-   页:1 `Container` 执行是一个直截了当的图形转录和字符串验证

在下一节提到的博客文章中.

### 兼容性

目前的实施既适用于遗留的实验装饰,也适用于新的TypeScript 5装饰. 如果装饰器在遗留的环境中使用,你就不会有错误解释你应该只使用 `Implements` 财务报告和审定财务报表 `Service` 课上装饰.

## 额外资源

-   [使用 ES 装饰器进行依赖性注射](https://blog.viktomas.com/graph/typescript-di-es-decorators/)
-   [类型脚本的装饰器类型](https://github.com/microsoft/TypeScript/pull/50820)
-   [ES 设计师提案](https://github.com/tc39/proposal-decorators)

## 常见问题

### @gitlab/needle 是什么？

@gitlab/needle 是TypeScript的轻量级依赖性注射框架,使用ES 第3级装饰\. 它为管理您 TypeScript 项目中的依赖性提供了一个类型安全解决方案 \.

### 如何安装 @gitlab/needle？

在项目目录运行 npm install @gitlab/needle，或使用 pnpm add / yarn add / bun add。

### @gitlab/needle 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @gitlab/needle 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @gitlab/needle 可以商用吗？

@gitlab/needle 使用 未声明 许可。package\.json 没有声明许可证。没有许可证的代码默认保留全部权利，商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括，不构成法律意见，请以许可原文为准。

### @gitlab/needle 的下载量有多少？

根据 npm 官方下载统计，@gitlab/needle 在 2026/10/17 – 2026/11/15 这 30 天内被下载 26,359 次，日均约 879 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @gitlab/needle 还在维护吗？

最新版本 2\.0\.0 发布于 2026/02/17（8 个月前）；至今共发布 10 个版本，其中过去 12 个月发布了 1 个；首次发布于 2025/02/07。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

