IversifyJS一个强大而轻量级的反转控件(IoC)容器,适用于由TypeScript编写的JavaScript和Node.js应用。它使用类构造函数去定义和注入它的依赖。IversifyJSAPI友好易懂,鼓励对OOP和IoC最佳实践的应用。
IversifyJS有4个主要目标:
允许JavaScript开发人员编写遵循SOLID原则的代码。
促进并鼓励遵守最佳的面向对象编程和依赖注入实践。
尽可能少的运行时开销。
提供艺术编程体验和生态。
使用步骤1:定义接口//fileiterfaces.tsexportiterfaceWarrior{fight():strig;seak():strig;}exportiterfaceWeapo{hit():strig;}exportiterfaceThrowableWeapo{throw():strig;}步骤2:定义依赖//fileetities.tsimport{ijectable,iject}from"iversify";import"reflect-metadata";import{Weapo,ThrowableWeapo,Warrior}from"./iterfaces";import{TYPES}from"./types";@ijectable()classKataaimplemetsWeapo{publichit(){retur"cut!";}}@ijectable()classShurikeimplemetsThrowableWeapo{publicthrow(){retur"hit!";}}@ijectable()classNijaimplemetsWarrior{private_kataa:Weapo;private_shurike:ThrowableWeapo;publiccostructor(@iject(TYPES.Weapo)kataa:Weapo,@iject(TYPES.ThrowableWeapo)shurike:ThrowableWeapo){this._kataa=kataa;this._shurike=shurike;}publicfight(){returthis._kataa.hit();}publicseak(){returthis._shurike.throw();}}export{Nija,Kataa,Shurike};步骤3:创建并配置IOC容器//fileiversify.cofig.tsimport{Cotaier}from"iversify";import{TYPES}from"./types";import{Warrior,Weapo,ThrowableWeapo}from"./iterfaces";import{Nija,Kataa,Shurike}from"./etities";costmyCotaier=ewCotaier();myCotaier.bid<Warrior>(TYPES.Warrior).to(Nija);myCotaier.bid<Weapo>(TYPES.Weapo).to(Kataa);myCotaier.bid<ThrowableWeapo>(TYPES.ThrowableWeapo).to(Shurike);export{myCotaier};步骤4:依赖解析import{myCotaier}from"./iversify.cofig";import{TYPES}from"./types";import{Warrior}from"./iterfaces";costija=myCotaier.get<Warrior>(TYPES.Warrior);expect(ija.fight()).eql("cut!");//trueexpect(ija.seak()).eql("hit!");//true
评论