@bonbons/di
TypeScript icon, indicating that this package has built-in type declarations

2.0.0-beta.3 • Public • Published

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");

Readme

Keywords

none

Package Sidebar

Install

npm i @bonbons/di

Weekly Downloads

1

Version

2.0.0-beta.3

License

MIT

Unpacked Size

103 kB

Total Files

57

Last publish

Collaborators

  • miao17game