1 Star 2 Fork 0

雷军 / di-example

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

DI(依赖注入) 示例

本项目是为了学习依赖注册的实现方式,如果有更好的方法可以通过 Issue 或者评论探讨。

本项目实现了以下功能:

  • Container(容器),用来管理依赖,功能包括依赖注册,依赖获取。
  • Provide 装饰器,用来注册依赖。
  • Inject 装饰器,用来注入依赖到实例对象。

使用方式

假设 A 类依赖 B 类,实现代码为:

//    ./services/a.ts
import Inject from '../inject'
import Provide from '../provide'
import B from './b'

// 通过 Provide 标记类并在初始化时注册到容器中
@Provide('a')
export default class A {
  // 通过 Inject 将 `B` 实例注入到 `b` 中
  @Inject('b')
  public b!: B;
}

//    ./services/b.ts
import Provide from '../provide'

// 通过 Provide 标记类并在初始化时注册到容器中
@Provide('b', [10])
export default class B {
  p: number;
  constructor(p: number) {
    this.p = p;
  }
}

接下来只需要调用 binding 完成依赖遍历、注册即可使用。可参看 binding 函数的实现,理解是如何实现所有依赖的注册的。

import { binding } from './container'
import container from './container'
import A from './services/a'

async function main() {
  // 此步必不可少
  await binding()
  const a: A = container.get('a')
  console.log(a.b); //B { p: 10 }
}

main()
MIT License Copyright (c) 2020 雷军 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

DI(依赖注入) 实例, 本项目是为了学习依赖注册的实现方式 展开 收起
TypeScript
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
TypeScript
1
https://gitee.com/lei2jun/di-example.git
git@gitee.com:lei2jun/di-example.git
lei2jun
di-example
di-example
master

搜索帮助