Skip to content
/ di Public

依赖注入node.js实现,提供底层的DI基架

License

Notifications You must be signed in to change notification settings

ws-Bonbons/di

Repository files navigation

Bonbons-DI

@bonbons/di

Build Status Coverage Status package version

依赖注入 node.js 实现

安装

npm install @bonbons/di --save
yarn add @bonbons/di

接入指南

import { DIContainer, InjectScope } from "@bonbons/di";
import { AbstractClass as Interface, ImplementClass as Implement } from "your/code";

// 创建di容器
const di = new DIContainer();

// 注入一个全局单例
di.register({ token: Interface, imp: Implement, scope: InjectScope.Singleton });

// 注入一个范围单例
di.register({ token: Interface, imp: Implement, scope: InjectScope.Scoped });

// 注入一个总是新建的实例
di.register({ token: Interface, imp: Implement, scope: InjectScope.New });

// 工厂方法来进行设置(最底层)
di.register({ token: Interface, imp: (scopeId?, {...}) => new Implement(...), scope: InjectScope.Singleton });

// 依赖注入工厂方法来进行设置
di.register({
  token: Interface,
  depts: [Class1, Class2],
  imp: (...args: [Class1, Class2]) => new Implement(...args),
  scope: InjectScope.Singleton
});

// 直接使用创建好的实例来解析
di.register({ token: Interface, imp: new Implement(...), scope: InjectScope.New });

// 完成解析构建
di.complete();

// 获取实例
const imp = di.get(Interface);

// 创建一个scope
di.createScope("scope_id", {...});

// 在某一个范围内获得实例
const scope_imp = di.get(Interface, "scope_id");

// 释放当前范围
di.dispose("scope_id");