欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Javascript技术栈中的四种依赖注入小结

程序员文章站 2022-07-20 17:00:56
作为面向对象编程中实现控制反转(inversion of control,下文称ioc)最常见的技术手段之一,依赖注入(dependency injection,下文称di...

作为面向对象编程中实现控制反转(inversion of control,下文称ioc)最常见的技术手段之一,依赖注入(dependency injection,下文称di)可谓在oop编程中大行其道经久不衰。比如在j2ee中,就有大名鼎鼎的执牛耳者spring。javascript社区中自然也不乏一些积极的尝试,广为人知的angularjs很大程度上就是基于di实现的。遗憾的是,作为一款缺少反射机制、不支持annotation语法的动态语言,javascript长期以来都没有属于自己的spring框架。当然,伴随着ecmascript草案进入快速迭代期的春风,javascript社区中的各种方言、框架可谓群雄并起,方兴未艾。可以预见到,优秀的javascriptdi框架的出现只是早晚的事。

本文总结了javascript中常见的依赖注入方式,并以inversify.js为例,介绍了方言社区对于javascript中di框架的尝试和初步成果。文章分为四节:

一. 基于injector、cache和函数参数名的依赖注入
二. angularjs中基于双injector的依赖注入
三. typescript中基于装饰器和反射的依赖注入
四. inversify.js——javascript技术栈中的ioc容器

一. 基于injector、cache和函数参数名的依赖注入

尽管javascript中不原生支持反射(reflection)语法,但是function.prototype上的tostring方法却为我们另辟蹊径,使得在运行时窥探某个函数的内部构造成为可能:tostring方法会以字符串的形式返回包含function关键字在内的整个函数定义。从这个完整的函数定义出发,我们可以利用正则表达式提取出该函数所需要的参数,从而在某种程度上得知该函数的运行依赖。
比如student类上write方法的函数签名write(notebook, pencil)就说明它的执行依赖于notebook和pencil对象。因此,我们可以首先把notebook和pencil对象存放到某个cache中,再通过injector(注入器、注射器)向write方法提供它所需要的依赖:

var cache = {};
// 通过解析function.prototype.tostring()取得参数名
function getparamnames(func) {
  // 正则表达式出自http://krasimirtsonev.com/blog/article/dependency-injection-in-javascript
  var paramnames = func.tostring().match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1];
  paramnames = paramnames.replace(/ /g, '');
  paramnames = paramnames.split(',');
  return paramnames;
}
var injector = {
  // 将func作用域中的this关键字绑定到bind对象上,bind对象可以为空
  resolve: function (func, bind) {
    // 取得参数名
    var paramnames = getparamnames(func);
    var params = [];
    for (var i = 0; i < paramnames.length; i++) {
      // 通过参数名在cache中取出相应的依赖
      params.push(cache[paramnames[i]]);
    }
    // 注入依赖并执行函数
    func.apply(bind, params);
  }
};
 
function notebook() {}
notebook.prototype.printname = function () {
  console.log('this is a notebook');
};
 
function pencil() {}
pencil.prototype.printname = function () {
  console.log('this is a pencil');
};
 
function student() {}
student.prototype.write = function (notebook, pencil) {
  if (!notebook || !pencil) {
    throw new error('dependencies not provided!');
  }
  console.log('writing...');
};
// 提供notebook依赖
cache['notebook'] = new notebook();
// 提供pencil依赖
cache['pencil'] = new pencil();
var student = new student();
injector.resolve(student.write, student); // writing...

有时候为了保证良好的封装性,也不一定要把cache对象暴露给外界作用域,更多的时候是以闭包变量或者私有属性的形式存在的:

function injector() {
  this._cache = {};
}
 
injector.prototype.put = function (name, obj) {
  this._cache[name] = obj;
};
 
injector.prototype.getparamnames = function (func) {
  // 正则表达式出自http://krasimirtsonev.com/blog/article/dependency-injection-in-javascript
  var paramnames = func.tostring().match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1];
  paramnames = paramnames.replace(/ /g, '');
  paramnames = paramnames.split(',');
  return paramnames;
};
 
injector.prototype.resolve = function (func, bind) {
  var self = this;
  var paramnames = self.getparamnames(func);
  var params = paramnames.map(function (name) {
    return self._cache[name];
  });
  func.apply(bind, params);
};
 
var injector = new injector();
 
var student = new student();
injector.put('notebook', new notebook());
injector.put('pencil', new pencil())
injector.resolve(student.write, student); // writing...

比如现在要执行student类上的另一个方法function draw(notebook, pencil, eraser),因为injector的cache中已经有了notebook和pencil对象,我们只需要将额外的eraser也存放到cache中:

function eraser() {}
eraser.prototype.printname = function () {
  console.log('this is an eraser');
};
 
// 为student增加draw方法
student.prototype.draw = function (notebook, pencil, eraser) {
  if (!notebook || !pencil || !eraser) {
    throw new error('dependencies not provided!');
  }
  console.log('drawing...');
};
 
injector.put('eraser', new eraser());
injector.resolve(student.draw, student);

通过依赖注入,函数的执行和其所依赖对象的创建逻辑就被解耦开来了。
当然,随着grunt/gulp/fis等前端工程化工具的普及,越来越多的项目在上线之前都经过了代码混淆(uglify),因而通过参数名去判断依赖并不总是可靠,有时候也会通过为function添加额外属性的方式来明确地说明其依赖:

student.prototype.write.depends = ['notebook', 'pencil'];
student.prototype.draw.depends = ['notebook', 'pencil', 'eraser'];
injector.prototype.resolve = function (func, bind) {
  var self = this;
  // 首先检查func上是否有depends属性,如果没有,再用正则表达式解析
  func.depends = func.depends || self.getparamnames(func);
  var params = func.depends.map(function (name) {
    return self._cache[name];
  });
  func.apply(bind, params);
};
var student = new student();
injector.resolve(student.write, student); // writing...
injector.resolve(student.draw, student); // draw...

二. angularjs中基于双injector的依赖注入

熟悉angularjs的同学很快就能联想到,在injector注入之前,我们在定义module时还可以调用config方法来配置随后会被注入的对象。典型的例子就是在使用路由时对$routeprovider的配置。也就是说,不同于上一小节中直接将现成对象(比如new notebook())存入cache的做法,angularjs中的依赖注入应该还有一个”实例化”或者”调用工厂方法”的过程。
这就是providerinjector、instanceinjector以及他们各自所拥有的providercache和instancecache的由来。
在angularjs中,我们能够通过依赖注入获取到的injector通常是instanceinjector,而providerinjector则是以闭包中变量的形式存在的。每当我们需要angularjs提供依赖注入服务时,比如想要获取notebook,instanceinjector会首先查询instancecache上是存在notebook属性,如果存在,则直接注入;如果不存在,则将这个任务转交给providerinjector;providerinjector会将”provider”字符串拼接到”notebook”字符串的后面,组成一个新的键名”notebookprovider”,再到providercache中查询是否有notebookprovider这个属性,如有没有,则抛出异常unknown provider异常:

如果有,则将这个provider返回给instanceinjector;instanceinjector拿到notebookprovider后,会调用notebookprovider上的工厂方法$get,获取返回值notebook对象,将该对象放到instancecache中以备将来使用,同时也注入到一开始声明这个依赖的函数中。

需要注意的是,angularjs中的依赖注入方式也是有缺陷的:利用一个instanceinjector单例服务全局的副作用就是无法单独跟踪和控制某一条依赖链条,即使在没有交叉依赖的情况下,不同module中的同名provider也会产生覆盖,这里就不详细展开了。

另外,对于习惯于java和c#等语言中高级ioc容器的同学来说,看到这里可能觉得有些别扭,毕竟在oop中,我们通常不会将依赖以参数的形式传递给方法,而是作为属性通过constructor或者setters传递给实例,以实现封装。的确如此,一、二节中的依赖注入方式没有体现出足够的面向对象特性,毕竟这种方式在javascript已经存在多年了,甚至都不需要es5的语法支持。希望了解javascript社区中最近一两年关于依赖注入的研究和成果的同学,可以继续往下阅读。

三. typescript中基于装饰器和反射的依赖注入

博主本身对于javascript的各种方言的学习并不是特别热情,尤其是现在emcascript提案、草案更新很快,很多时候借助于polyfill和babel的各种preset就能满足需求了。但是typescript是一个例外(当然现在decorator也已经是提案了,虽然阶段还比较早,但是确实已经有polyfill可以使用)。上文提到,javascript社区中迟迟没有出现一款优秀的ioc容器和自身的语言特性有关,那就依赖注入这个话题而言,typescript给我们带来了什么不同呢?至少有下面这几点:
* typescript增加了编译时类型检查,使javascript具备了一定的静态语言特性
* typescript支持装饰器(decorator)语法,和传统的注解(annotation)颇为相似
* typescript支持元信息(metadata)反射,不再需要调用function.prototype.tostring方法
下面我们就尝试利用typescript带来的新语法来规范和简化依赖注入。这次我们不再向函数或方法中注入依赖了,而是向类的构造函数中注入。
typescript支持对类、方法、属性和函数参数进行装饰,这里需要用到的是对类的装饰。继续上面小节中用到的例子,利用typescript对代码进行一些重构:

class pencil {
  public printname() {
    console.log('this is a pencil');
  }
}
 
class eraser {
  public printname() {
    console.log('this is an eraser');
  }
}
 
class notebook {
  public printname() {
    console.log('this is a notebook');
  }
}
 
class student {
  pencil: pencil;
  eraser: eraser;
  notebook: notebook;
  public constructor(notebook: notebook, pencil: pencil, eraser: eraser) {
    this.notebook = notebook;
    this.pencil = pencil;
    this.eraser = eraser;
  }
  public write() {
    if (!this.notebook || !this.pencil) {
      throw new error('dependencies not provided!');
    }
    console.log('writing...');
  }
  public draw() {
    if (!this.notebook || !this.pencil || !this.eraser) {
      throw new error('dependencies not provided!');
    }
    console.log('drawing...');
  }
}

下面是injector和装饰器inject的实现。injector的resolve方法在接收到传入的构造函数时,会通过name属性取出该构造函数的名字,比如class student,它的name属性就是字符串”student”。再将student作为key,到dependenciesmap中去取出student的依赖,至于dependenciesmap中是何时存入的依赖关系,这是装饰器inject的逻辑,后面会谈到。student的依赖取出后,由于这些依赖已经是构造函数的引用而非简单的字符串了(比如notebook、pencil的构造函数),因此直接使用new语句即可获取这些对象。获取到student类所依赖的对象之后,如何把这些依赖作为构造函数的参数传入到student中呢?最简单的莫过于es6的spread操作符。在不能使用es6的环境下,我们也可以通过伪造一个构造函数来完成上述逻辑。注意为了使instanceof操作符不失效,这个伪造的构造函数的prototype属性应该指向原构造函数的prototype属性。

var dependenciesmap = {};
var injector = {
  resolve: function (constructor) {
    var dependencies = dependenciesmap[constructor.name];
    dependencies = dependencies.map(function (dependency) {
      return new dependency();
    });
    // 如果可以使用es6的语法,下面的代码可以合并为一行:
    // return new constructor(...dependencies);
    var mockconstructor: any = function () {
      constructor.apply(this, dependencies);
    };
    mockconstructor.prototype = constructor.prototype;
    return new mockconstructor();
  }
};
function inject(...dependencies) {
  return function (constructor) {
    dependenciesmap[constructor.name] = dependencies;
    return constructor;
  };
}

injector和装饰器inject的逻辑完成后,就可以用来装饰class student并享受依赖注入带来的乐趣了:

// 装饰器的使用非常简单,只需要在类定义的上方添加一行代码
// inject是装饰器的名字,后面是function inject的参数
@inject(notebook, pencil, eraser)
class student {
  pencil: pencil;
  eraser: eraser;
  notebook: notebook;
  public constructor(notebook: notebook, pencil: pencil, eraser: eraser) {
    this.notebook = notebook;
    this.pencil = pencil;
    this.eraser = eraser;
  }
  public write() {
    if (!this.notebook || !this.pencil) {
      throw new error('dependencies not provided!');
    }
    console.log('writing...');
  }
  public draw() {
    if (!this.notebook || !this.pencil || !this.eraser) {
      throw new error('dependencies not provided!');
    }
    console.log('drawing...');
  }
}
var student = injector.resolve(student);
console.log(student instanceof student); // true
student.notebook.printname(); // this is a notebook
student.pencil.printname(); // this is a pencil
student.eraser.printname(); // this is an eraser
student.draw(); // drawing
student.write(); // writing

利用装饰器,我们还可以实现一种比较激进的依赖注入,下文称之为radicalinject。radicalinject对原代码的侵入性比较强,不一定适合具体的业务,这里也一并介绍一下。要理解radicalinject,需要对typescript装饰器的原理和array.prototype上的reduce方法理解比较到位。

function radicalinject(...dependencies){
  var wrappedfunc:any = function (target: any) {
    dependencies = dependencies.map(function (dependency) {
      return new dependency();
    });
    // 使用mockconstructor的原因和上例相同
    function mockconstructor() {
      target.apply(this, dependencies);
    }
    mockconstructor.prototype = target.prototype;
 
    // 为什么需要使用reservedconstructor呢?因为使用radicalinject对student方法装饰之后,
    // student指向的构造函数已经不是一开始我们声明的class student了,而是这里的返回值,
    // 即reservedconstructor。student的指向变了并不是一件不能接受的事,但是如果要
    // 保证student instanceof student如我们所期望的那样工作,这里就应该将
    // reservedconstructor的prototype属性指向原student的prototype
    function reservedconstructor() {
      return new mockconstructor();
    }
    reservedconstructor.prototype = target.prototype;
    return reservedconstructor;
  }
  return wrappedfunc;
}

使用radicalinject,原构造函数实质上已经被一个新的函数代理了,使用上也更为简单,甚至都不需要再有injector的实现:

@radicalinject(notebook, pencil, eraser)
class student {
  pencil: pencil;
  eraser: eraser;
  notebook: notebook;
  public constructor() {}
  public constructor(notebook: notebook, pencil: pencil, eraser: eraser) {
    this.notebook = notebook;
    this.pencil = pencil;
    this.eraser = eraser;
  }
  public write() {
    if (!this.notebook || !this.pencil) {
      throw new error('dependencies not provided!');
    }
    console.log('writing...');
  }
  public draw() {
    if (!this.notebook || !this.pencil || !this.eraser) {
      throw new error('dependencies not provided!');
    }
    console.log('drawing...');
  }
}
// 不再出现injector,直接调用构造函数
var student = new student(); 
console.log(student instanceof student); // true
student.notebook.printname(); // this is a notebook
student.pencil.printname(); // this is a pencil
student.eraser.printname(); // this is an eraser
student.draw(); // drawing
student.write(); // writing

由于class student的constructor方法需要接收三个参数,直接无参调用new student()会造成typescript编译器报错。当然这里只是分享一种思路,大家可以暂时忽略这个错误。有兴趣的同学也可以使用类似的思路尝试代理一个工厂方法,而非直接代理构造函数,以避免这类错误,这里不再展开。

angularjs2团队为了获得更好的装饰器和反射语法的支持,一度准备另起炉灶,基于atscript(atscript中的”a”指的就是annotation)来进行新框架的开发。但最终却选择拥抱typescript,于是便有了微软和谷歌的奇妙组合。

当然,需要说明的是,在缺少相关标准和浏览器厂商支持的情况下,typescript在运行时只是纯粹的javascript,下节中出现的例子会印证这一点。

四. inversify.js——javascript技术栈中的ioc容器

其实从javascript出现各种支持高级语言特性的方言就可以预见到,ioc容器的出现只是早晚的事情。比如博主今天要介绍的基于typescript的inversify.js,就是其中的先行者之一。
inversity.js比上节中博主实现的例子还要进步很多,它最初设计的目的就是为了前端工程师同学们能在javascript中写出符合solid原则的代码,立意可谓非常之高。表现在代码中,就是处处有接口,将”depend upon abstractions. do not depend upon concretions.”(依赖于抽象,而非依赖于具体)表现地淋漓尽致。继续使用上面的例子,但是由于inversity.js是面向接口的,上面的代码需要进一步重构:

interface notebookinterface {
  printname(): void;
}
interface pencilinterface {
  printname(): void;
}
interface eraserinterface {
  printname(): void;
}
interface studentinterface {
  notebook: notebookinterface;
  pencil: pencilinterface;
  eraser: eraserinterface;
  write(): void;
  draw(): void;
}
class notebook implements notebookinterface {
  public printname() {
    console.log('this is a notebook');
  }
}
class pencil implements pencilinterface {
  public printname() {
    console.log('this is a pencil');
  }
}
class eraser implements eraserinterface {
  public printname() {
    console.log('this is an eraser');
  }
}
 
class student implements studentinterface {
  notebook: notebookinterface;
  pencil: pencilinterface;
  eraser: eraserinterface;
  constructor(notebook: notebookinterface, pencil: pencilinterface, eraser: eraserinterface) {
    this.notebook = notebook;
    this.pencil = pencil;
    this.eraser = eraser;
  }
  write() {
    console.log('writing...');
  }
  draw() {
    console.log('drawing...');
  }
}

由于使用了inversity框架,这次我们就不用自己实现injector和inject装饰器啦,只需要从inversify模块中引用相关对象:

import { inject } from "inversify";
 
@inject("notebookinterface", "pencilinterface", "eraserinterface")
class student implements studentinterface {
  notebook: notebookinterface;
  pencil: pencilinterface;
  eraser: eraserinterface;
  constructor(notebook: notebookinterface, pencil: pencilinterface, eraser: eraserinterface) {
    this.notebook = notebook;
    this.pencil = pencil;
    this.eraser = eraser;
  }
  write() {
    console.log('writing...');
  }
  draw() {
    console.log('drawing...');
  }
}

这样就行了吗?还记得上节中提到typescript中各种概念只是语法糖吗?不同于上一节中直接将constructor引用传递给inject的例子,由于inversify.js是面向接口的,而诸如notebookinterface、pencilinterface之类的接口只是由typescript提供的语法糖,在运行时并不存在,因此我们在装饰器中声明依赖时只能使用字符串形式而非引用形式。不过不用担心,inversify.js为我们提供了bind机制,在接口的字符串形式和具体的构造函数之间搭建了桥梁:

import { typebinding, kernel } from "inversify";
 
var kernel = new kernel();
kernel.bind(new typebinding("notebookinterface", notebook));
kernel.bind(new typebinding("pencilinterface", pencil));
kernel.bind(new typebinding("eraserinterface", eraser));
kernel.bind(new typebinding("studentinterface", student));

注意这步需要从inversify模块中引入typebinding和kernel,并且为了保证返回值类型以及整个编译时静态类型检查能够顺利通过,泛型语法也被使用了起来。
说到这里,要理解new typebinding(“notebookinterface”, notebook)也就很自然了:为依赖于”notebookinterface”字符串的类提供notebook类的实例,返回值向上溯型到notebookinterface。
完成了这些步骤,使用起来也还算顺手:

var student: studentinterface = kernel.resolve("studentinterface");
console.log(student instanceof student); // true
student.notebook.printname(); // this is a notebook
student.pencil.printname(); // this is a pencil
student.eraser.printname(); // this is an eraser
student.draw(); // drawing
student.write(); // writing

最后,顺带提一下ecmascript中相关提案的现状和进展。google的atscript团队曾经有过annotation的提案,但是atscript胎死腹中,这个提案自然不了了之了。目前比较有希望成为es7标准的是一个关于装饰器的提案:。感兴趣的同学可以到相关的github页面跟踪了解。尽管di只是oop编程众多模式和特性中的一个,但却可以折射出javascript在oop上艰难前进的道路。但总得说来,也算得上是路途坦荡,前途光明。回到依赖注入的话题上,一边是翘首以盼的javascript社区,一边是姗姗来迟的ioc容器,这二者最终能产生怎样的化学反应,让我们拭目以待。