dp-mqueue
v1.0.4
Published
javascript typescript dp uni framework queue node.js
Downloads
2
Readme
dp-ioc
简单、强大的基于TypeScript的IOC库。
一、安装 [ Installation ]
- npm i dp-ioc
二、快速开始
import { Inject, Injectable, Provider } from "dp-ioc";
//定义一个可注入类
@Injectable()
class Person {
name = "rajan"
dance() {
return this.name + " dance";
}
}
// 注入到其他类中
class ClassRoom {
@Inject(Person)
public person:Person;
}
// 使用,(通过Provider函数进行实例化 )
let classRoom = Provider<ClassRoom>(ClassRoom);
console.log(classRoom.person.name); // rajan
console.log(classRoom.person.dance); // rajan dance
注意,使用了依赖注入的类,在应用时必须通过Provider进行实例化
三、高级用法
3.1 单例
import { Single, Injectable } from "dp-ioc";
@Single()
@Injectable()
class Person {
name = "rajan"
dance() {
return this.name + " dance";
}
}
3.2 多层注入
import { Single, Injectable,Inject,Provider } from "dp-ioc";
@Injectable()
class Person {
name = "rajan"
dance() {
return this.name + " dance";
}
}
@Injectable()
class ClassRoom {
name = "room 001"
@Inject(Person)
person:Person
}
class School {
@Inject(ClassRoom)
classRoom:ClassRoom;
}
let school = Provider<School>(School);
3.3 构造传参
本库支持实例化Injectable可注入对象时,传入实例化的参数
import { Single, Injectable,Inject,Provider,Constructor } from "dp-ioc";
@Injectable()
class Person {
name = "rajan"
age = 0;
//ioc 容器实例化该类时,setPersonBasicInfo方法将会被执行
@Constructor()
setPersonBasicInfo(name:string,age:number){
this.name = name;
this.age = age;
}
dance() {
return this.name + " dance";
}
}
//注入
class ClassRoom {
name = "room 001"
@Inject(Person,["小明",18])
person:Person
}
// 实例化
let classRoom = Provider<ClassRoom>(ClassRoom);
console.log(classRoom.person.name,classRoom.person.age); // 小明 18
3.4 支持继承依赖
import { Single, Injectable,Inject,Provider,Constructor } from "dp-ioc";
@Injectable()
class Human {
age = 0;
name = "";
}
class Student extends Human {
dance():string{
return this.name + "dance";
}
}
class classRoom {
@Inject(Student)
public Student: Student;
}
3.5 序列化和反序列
在实际项目开发中,某些对象可能需要序列化为字符串以便存储,传输。本库支持将序列化之后的对象还原为依赖对象。
import { Single, Injectable,Inject,Provider,Constructor } from "dp-ioc";
@Injectable()
class Person {
age = 0;
name = "";
dance():string{
return this.name + "dance";
}
}
class ClassRoom {
@Inject(Student)
public Student: Student;
}
let classRoom = Provider<ClassRoom>(ClassRoom);
let classRoomStr = JSON.stringify(classRoom); // 序列化为字符串
classRoom = Provider<ClassRoom>(ClassRoom,JSON.parse(classRoomStr)); // 反序列化为依赖对象
四、支持
如果在使用过程中,遇到问题,请到github仓库反馈,仓库地址。