-
Notifications
You must be signed in to change notification settings - Fork 17
plugins
Exodia edited this page Jun 12, 2016
·
1 revision
为了满足对uioc功能扩展的场景,uioc针对各个生命周期阶段都提供了对应的扩展点,同时也提供了一系列面向插件的操作接口,使用者可以编写插件对uioc进行个性化的扩展。
在介绍插件接口之前先简要介绍下下uioc的各个生命周期阶段:
- 容器初始化阶段
- 注册组件阶段
- 获取组件阶段
- 创建实例前阶段
- 创建实例后阶段
- 容器销毁阶段
每个插件都要实现ILifeCircleHook接口,ILifeCircleHook的每个方法都对应了上述的各个生命周期阶段。
为了编写方便,uioc提供了BasePlugin抽象类,提供了各个生命周期方法的一套默认实现(不做任何事),插件开发者可以继承BasePlugin来覆盖各个生命周期方法以实现自己的扩展需求。
插件编写好后,需要将插件添加至uioc中,可以在uioc容器创建阶段通过plugins配置的方式加入,也可以在容器实例上调用addPlugins方法加入插件。
各个插件在同个生命周期方法的执行顺序为先注册先执行
import {IoC, BasePlugin} from 'ioc';
// 自定义插件
class TrackerPlugin extends BasePlugin {
get name() {
return 'tracker';
}
onContainerInit(ioc, iocConfig) {
console.log('onContainerInit, container config is: ', iocConfig);
return super.onContainerInit(ioc, iocConfig);
}
onAddComponent(ioc, componentId, componentConfig) {
console.log('onAddComponent, component config is: ', componentConfig);
return super.onAddComponent(ioc, componentId, componentConfig);
}
onGetComponent(ioc, componentId, componentConfig) {
console.log('onGetComponent, component config is: ', componentConfig);
return super.onGetComponent(ioc, componentId, componentConfig);
}
beforeCreateInstance(ioc, componentId, instance) {
console.log('beforeCreateInstance, component id is: ', componentId);
return super.beforeCreateInstance(ioc, componentId, instance);
}
afterCreateInstance(ioc, componentId, instance) {
console.log('afterCreateInstance, component id is: ', componentId);
return super.afterCreateInstance(ioc, componentId, instance);
}
onContainerDispose(ioc) {
console.log('onContainerDispose');
return super.onContainerDispose(ioc);
}
}
let ioc = new IoC({
// 注册插件
plugins: [new TrackerPlugin()],
components: {
list: {
creator: class List {}
}
}
});
// 也可以通过实例方法添加插件
// ioc.addPlugins([new TrackerPlugin()]);
ioc.getComponent('list').then(list => {});
上述代码中展示了一个跟踪uioc生命周期的插件,会在生命周期每一个阶段都打印相关信息。