InversifyJS一个强大而轻量级的反转控件(IoC)容器,适用于由TypeScript编写的JavaScript和Node.js应用。它使用类构造函数去定义和注入它的依赖。InversifyJSAPI友好易懂,鼓励对OOP和IoC最佳实践的应用。
InversifyJS有4个主要目标:
允许JavaScript开发人员编写遵循SOLID原则的代码。
促进并鼓励遵守最佳的面向对象编程和依赖注入实践。
尽可能少的运行时开销。
提供艺术编程体验和生态。
使用步骤1:定义接口//fileinterfaces.tsexportinterfaceWarrior{fight():string;sneak():string;}exportinterfaceWeapon{hit():string;}exportinterfaceThrowableWeapon{throw():string;}步骤2:定义依赖//fileentities.tsimport{injectable,inject}from"inversify";import"reflect-metadata";import{Weapon,ThrowableWeapon,Warrior}from"./interfaces";import{TYPES}from"./types";@injectable()classKatanaimplementsWeapon{publichit(){return"cut!";}}@injectable()classShurikenimplementsThrowableWeapon{publicthrow(){return"hit!";}}@injectable()classNinjaimplementsWarrior{private_katana:Weapon;private_shuriken:ThrowableWeapon;publicconstructor(@inject(TYPES.Weapon)katana:Weapon,@inject(TYPES.ThrowableWeapon)shuriken:ThrowableWeapon){this._katana=katana;this._shuriken=shuriken;}publicfight(){returnthis._katana.hit();}publicsneak(){returnthis._shuriken.throw();}}export{Ninja,Katana,Shuriken};步骤3:创建并配置IOC容器//fileinversify.config.tsimport{Container}from"inversify";import{TYPES}from"./types";import{Warrior,Weapon,ThrowableWeapon}from"./interfaces";import{Ninja,Katana,Shuriken}from"./entities";constmyContainer=newContainer();myContainer.bind<Warrior>(TYPES.Warrior).to(Ninja);myContainer.bind<Weapon>(TYPES.Weapon).to(Katana);myContainer.bind<ThrowableWeapon>(TYPES.ThrowableWeapon).to(Shuriken);export{myContainer};步骤4:依赖解析import{myContainer}from"./inversify.config";import{TYPES}from"./types";import{Warrior}from"./interfaces";constninja=myContainer.get<Warrior>(TYPES.Warrior);expect(ninja.fight()).eql("cut!");//trueexpect(ninja.sneak()).eql("hit!");//true
评论