其他分享
首页 > 其他分享> > inversify 强大&&轻量级的基于typescript 的ioc 框架

inversify 强大&&轻量级的基于typescript 的ioc 框架

作者:互联网

inversify 强大&&轻量级的基于typescript 的ioc 框架,以前有介绍过一个typedi 的类似框架
inversify github 的star比typedi 多很多

参考使用

 
{
    "compilerOptions": {
        "target": "es5",
        "lib": ["es6"],
        "types": ["reflect-metadata"],
        "module": "commonjs",
        "moduleResolution": "node",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true
    }
}
// file interfaces.ts
export interface Warrior {
    fight(): string;
    sneak(): string;
}
export interface Weapon {
    hit(): string;
}
export interface ThrowableWeapon {
    throw(): string;
}
   
// file types.ts
const TYPES = {
    Warrior: Symbol.for("Warrior"),
    Weapon: Symbol.for("Weapon"),
    ThrowableWeapon: Symbol.for("ThrowableWeapon")
};
export { TYPES };
// file entities.ts
import { injectable, inject } from "inversify";
import "reflect-metadata";
import { Weapon, ThrowableWeapon, Warrior } from "./interfaces";
import { TYPES } from "./types";
@injectable()
class Katana implements Weapon {
    public hit() {
        return "cut!";
    }
}
@injectable()
class Shuriken implements ThrowableWeapon {
    public throw() {
        return "hit!";
    }
}
@injectable()
class Ninja implements Warrior {
    private _katana: Weapon;
    private _shuriken: ThrowableWeapon;
    public constructor(
      @inject(TYPES.Weapon) katana: Weapon,
      @inject(TYPES.ThrowableWeapon) shuriken: ThrowableWeapon
    ) {
        this._katana = katana;
        this._shuriken = shuriken;
    }
    public fight() { return this._katana.hit(); }
    public sneak() { return this._shuriken.throw(); }
}
export { Ninja, Katana, Shuriken };
   
// file inversify.config.ts
import { Container } from "inversify";
import { TYPES } from "./types";
import { Warrior, Weapon, ThrowableWeapon } from "./interfaces";
import { Ninja, Katana, Shuriken } from "./entities";
const myContainer = new Container();
myContainer.bind<Warrior>(TYPES.Warrior).to(Ninja);
myContainer.bind<Weapon>(TYPES.Weapon).to(Katana);
myContainer.bind<ThrowableWeapon>(TYPES.ThrowableWeapon).to(Shuriken);
export { myContainer };
   
import { myContainer } from "./inversify.config";
import { TYPES } from "./types";
import { Warrior } from "./interfaces";
const ninja = myContainer.get<Warrior>(TYPES.Warrior);
console.log(ninja.fight()); 
console.log(ninja.sneak())

说明

inversify 是一个不错的ioc 可选类库

参考资料

https://github.com/typestack/typedi
https://github.com/inversify/InversifyJS
https://github.com/rongfengliang/inversify-lerning

标签:Warrior,typescript,inversify,ThrowableWeapon,轻量级,import,Weapon,TYPES
来源: https://www.cnblogs.com/rongfengliang/p/12879488.html