Context 手册
plugin 服务使用 Context 向插件提供上下文。每个插件的上下文绑定到独立的子作用域(见 核心概念):插件登记的资源归属自身,卸载时随子作用域一并释放,不会污染其他插件。
读取服务
上下文拥有 get / has / list 方法,沿作用域父链读取服务:
typescript
export const inject = ['external-service'];
export const name = 'my-plugin';
export default function (context: Context) {
console.log(context.get('external-service')); // external-service 服务的实例
console.log(context.has('logger')); // true:沿父链可见
console.log(context.list()); // 父链可见的全部登记名
}- 读取沿父链逐层委托,服务替换后读到的始终是最新实例;
- 未声明
inject的服务也可读取(全量可读);inject的价值在于依赖编排(等待、顺序、级联),见 依赖与诊断; get未命中返回undefined——服务插件被禁用时,其共享的服务会被摘除,消费方读取得到undefined。
类型提示通过 ServiceRegistry 声明扩展获得:
typescript
import type { LoggerService } from '@saukkojs/core';
declare module '@saukkojs/core' {
interface ServiceRegistry {
myService: MyService;
}
}登记资源
插件可以向自己的子作用域登记资源:
typescript
export default function (context: Context) {
context.set('cache', new Map()); // 纯登记
context.register('helper', HelperService); // 惰性注册,支持静态 inject
await context.provide('worker', worker); // 带 start/stop 生命周期管理
}这些登记只对插件自己可见,卸载时随之释放。provide 的服务若实现 start / stop 约定,会随插件子作用域的生命周期启动与停止。
提供服务:share
set / register / provide 的登记对兄弟插件不可见。要对其他插件提供服务,使用 share 将服务提升到根作用域:
typescript
export const name = 'my-service';
export default async function (context: Context) {
await context.share('myService', new MyService()); // 显式服务名
await context.share(new MyService()); // 缺省为插件名
}提升的服务随插件启用而启动、随禁用而从根作用域摘除、随卸载而清理,是"服务即插件"的对外提供路径。详见 编写服务 与 服务生命周期。
插件配置
上下文拥有 config 属性,包含指定给插件的配置(配置文件的 plugin.config.<插件名>):
typescript
export default function (context: Context) {
console.log(context.config); // my-plugin 插件在配置文件中的属性
}事件
上下文实现了与 EventEmitter 相似的 API,用于处理来自框架内部与聊天平台的事件:
typescript
export default function (context: Context) {
context.on('message.private', (event) => {
event.bot.sendPrivateMessage(event.data.author.id, event.data.content);
});
}on返回取消监听的函数;off手动移除;emit同步分发事件。- disabled 插件不接收事件:禁用期间监听被门控,重新启用后自动恢复。
- 事件监听在插件卸载时自动移除,无需手动
off。
机器人实例
上下文拥有一个 bots 数组,包含已挂载的聊天平台适配器实例;适配器插件通过 context.mountBot(bot) 挂载,详见 适配器开发。
生命周期
context.lifecycle 用于注册清理钩子与观察状态,详见 生命周期与清理。