简介
injector是用来做参数自动注入的,例如
ng在运行时会把$http,aService 自动作为参数传入进行执行。
其实很容易想明白,injector做了两件事
- 缓存那些service,以后作为参数注入
- 分析参数列表,找到需要的参数注入
下面源码分析如何实现上面两件事情。
结构
createInjector -> createInternalInjector return: instanceInjector
所以 createInjector() 返回的是 instanceInjector,结构如下:
源码分析
调用注册service等
providerCache = {
$provide: {
provider: supportObject(provider),factory: supportObject(factory),service: supportObject(service),value: supportObject(value),constant: supportObject(constant),decorator: decorator
}
},// providerInjector,instanceInjector 两个注入器
// instanceInjector对外提供service等注入,providerInjector对内提供provider获取
providerInjector = (providerCache.$injector =
createInternalInjector(providerCache,function() {
throw $injectorMinErr('unpr',"Unknown provider: {0}",path.join(' <- '));
},strictDi)),instanceCache = {},instanceInjector = (instanceCache.$injector =
createInternalInjector(instanceCache,function(servicename) {
var provider = providerInjector.get(servicename + providerSuffix);
return instanceInjector.invoke(provider.$get,provider,undefined,servicename);
},strictDi));
// 加载模块
forEach(loadModules(modulesToLoad),function(fn) { instanceInjector.invoke(fn || noop); });
return instanceInjector;
}
用于包装方法,包装前的方法接受两个参数 (key,value),经过包装后的方法能支持传入object参数,即多个 key -> value。
回顾下provider、service 和 factory的使用方式
app.service('serviceName',function(){
this.getName = function() {}
this.setName = function() {}
});
app.provider('serviceName',function($httpProvider){
// 注入$httpProvider
this.$get = function() {
return {
getName: function(){},setName: function(){}
};
}
});
app.provider('serviceName',{
$get: function () {}
});
function provider(name,provider_) {
assertNotHasOwnProperty(name,'service');
// 当provider是fn或者array时可以将其他provider注入到参数
// 因为providerInjector.instantiate(provider)时可以传入依赖的其他provider
// 这也是provider与service,factory方法不一样的地方
if (isFunction(provider) || isArray(provider)) {
provider = providerInjector.instantiate(provider);
}
if (!provider.$get) {
throw $injectorMinErr('pget',"Provider '{0}' must define $get factory method.",name);
}
return providerCache[name + providerSuffix] = provider;
}
function factory(name,factoryFn) { return provider(name,{ $get: factoryFn }); }
function service(name,constructor) {
return factory(name,['$injector',function($injector) {
return $injector.instantiate(constructor);
}]);
}
function value(name,val) { return factory(name,valueFn(val)); }
最终汇总到provider的实现,将provider缓存到providerCache,供调用
跟其他不一样的就是constant的实现,分别保存到providerCache和instanceCache中,这样在定义provider还是在定义service是都能注入。
调用$provid的factory,service等
provider[invokeArgs[1]].apply(provider,invokeArgs[2]);
}
}
示例:
使用示例看出,传入的参数$delegate是原先的service实例,需要在该实例上添加方法都可以,即所谓的装饰器
源码:
origProvider.$get = function() {
// 通过上面获取的provider生成需要的service实例,再以$delegate注入到参数列表
var origInstance = instanceInjector.invoke(orig$get,origProvider);
return instanceInjector.invoke(decorFn,null,{$delegate: origInstance});
};
}
3. createInternalInjector
// 从cache中获取,没有的话调用factory进行创建,具体看getService解析
function getService(serviceName) {
}
function invoke(fn,self,locals,serviceName){
}
function instantiate(Type,serviceName) {
}
return {
// 执行fn,具有参数注入功能
invoke: invoke,// 实例化fn,可以参数注入
instantiate: instantiate,// 获取provider或者service
get: getService,// 获取方法的参数列表,供注入使用
annotate: annotate,// 确认是否含有provider或service
has: function(name) {
return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
}
};
}
获取fn的参数列表
['a','b','c']
// type2
['a',fn] -> ['a','b']
// type3
function fn () {}
fn.$inject = ['a','c']
-> ['a','c']
源码:
if (typeof fn === 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
if (fn.length) {
// 严格模式下或抛错
if (strictDi) {
if (!isString(name) || !name) {
name = fn.name || anonFn(fn);
}
throw $injectorMinErr('strictdi','{0} is not using explicit annotation and cannot be invoked in strict mode',name);
}
// 将注释去掉
fnText = fn.toString().replace(STRIP_COMMENTS,'');
// 将参数全部选出fn(a,c,d) -> 'a,d'
argDecl = fnText.match(FN_ARGS);
// 分割成array
forEach(argDecl[1].split(FN_ARG_SPLIT),function(arg){
arg.replace(FN_ARG,function(all,underscore,name){
$inject.push(name);
});
});
}
fn.$inject = $inject;
}
} else if (isArray(fn)) {
last = fn.length - 1;
assertArgFn(fn[last],'fn');
$inject = fn.slice(0,last);
} else {
assertArgFn(fn,'fn',true);
}
return $inject;
}
标记
// 因为接下来调用factory(serviceName),其实是一个递归调用
// function(servicename) {
// var provider = providerInjector.get(servicename + providerSuffix);
// return instanceInjector.invoke(provider.$get,servicename);
// }
// instanceInjector.invoke(provider.$get 时会将需要注入的参数get出来然后注入
// 因此做上标记后就可以判断是否有循环依赖
function getService(serviceName) {
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] === INSTANTIATING) {
throw $injectorMinErr('cdep','Circular dependency found: {0}',serviceName + ' <- ' + path.join(' <- '));
}
return cache[serviceName];
} else {
try {
path.unshift(serviceName);
cache[serviceName] = INSTANTIATING;
return cache[serviceName] = factory(serviceName);
} catch (err) {
if (cache[serviceName] === INSTANTIATING) {
delete cache[serviceName];
}
throw err;
} finally {
path.shift();
}
}
}
var args = [],// 获取参数列表
$inject = annotate(fn,serviceName),length,i,key;
for(i = 0,length = $inject.length; i < length; i++) {
key = $inject[i];
if (typeof key !== 'string') {
throw $injectorMinErr('itkn','Incorrect injection token! Expected service name as string,got {0}',key);
}
// locals优先
args.push(
locals && locals.hasOwnProperty(key)
? locals[key]
: getService(key)
);
}
if (isArray(fn)) {
fn = fn[length];
}
return fn.apply(self,args);
}
// 当type为array时,获取最后的参数如:['$window',function($win){}]
Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
instance = new Constructor();
// 调用invoke执行Type方法
returnedValue = invoke(Type,serviceName);
return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
}
// 加载模块
forEach(loadModules(modulesToLoad),function(fn) { instanceInjector.invoke(fn || noop); });
return instanceInjector;
}
用于包装方法,包装前的方法接受两个参数 (key,value),经过包装后的方法能支持传入object参数,即多个 key -> value。
回顾下provider、service 和 factory的使用方式 this.setName = function() {} app.provider('serviceName',function($httpProvider){ app.provider('serviceName',{ function factory(name,factoryFn) { return provider(name,{ $get: factoryFn }); } function service(name,constructor) { function value(name,val) { return factory(name,valueFn(val)); } 最终汇总到provider的实现,将provider缓存到providerCache,供调用 跟其他不一样的就是constant的实现,分别保存到providerCache和instanceCache中,这样在定义provider还是在定义service是都能注入。
示例: 使用示例看出,传入的参数$delegate是原先的service实例,需要在该实例上添加方法都可以,即所谓的装饰器 源码: 3. createInternalInjector
this.getName = function() {}
});
// 注入$httpProvider
this.$get = function() {
return {
getName: function(){},setName: function(){}
};
}
});
$get: function () {}
});
function provider(name,provider_) {
assertNotHasOwnProperty(name,'service');
// 当provider是fn或者array时可以将其他provider注入到参数
// 因为providerInjector.instantiate(provider)时可以传入依赖的其他provider
// 这也是provider与service,factory方法不一样的地方
if (isFunction(provider) || isArray(provider)) {
provider = providerInjector.instantiate(provider);
}
if (!provider.$get) {
throw $injectorMinErr('pget',"Provider '{0}' must define $get factory method.",name);
}
return providerCache[name + providerSuffix] = provider;
}
return factory(name,['$injector',function($injector) {
return $injector.instantiate(constructor);
}]);
}
// 通过上面获取的provider生成需要的service实例,再以$delegate注入到参数列表
var origInstance = instanceInjector.invoke(orig$get,origProvider);
return instanceInjector.invoke(decorFn,null,{$delegate: origInstance});
};
}
// 从cache中获取,没有的话调用factory进行创建,具体看getService解析
}
function invoke(fn,self,locals,serviceName){
}
function instantiate(Type,serviceName) {
}
return {
// 执行fn,具有参数注入功能
invoke: invoke,// 实例化fn,可以参数注入
instantiate: instantiate,// 获取provider或者service
get: getService,// 获取方法的参数列表,供注入使用
annotate: annotate,// 确认是否含有provider或service
has: function(name) {
return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
}
};
}
获取fn的参数列表 // type2 // type3 源码:
for(i = 0,length = $inject.length; i < length; i++) { return fn.apply(self,args);
return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
['a',fn] -> ['a','b']
function fn () {}
fn.$inject = ['a','c']
-> ['a','c']
if (!($inject = fn.$inject)) {
$inject = [];
if (fn.length) {
// 严格模式下或抛错
if (strictDi) {
if (!isString(name) || !name) {
name = fn.name || anonFn(fn);
}
throw $injectorMinErr('strictdi','{0} is not using explicit annotation and cannot be invoked in strict mode',name);
}
// 将注释去掉
fnText = fn.toString().replace(STRIP_COMMENTS,'');
// 将参数全部选出fn(a,c,d) -> 'a,d'
argDecl = fnText.match(FN_ARGS);
// 分割成array
forEach(argDecl[1].split(FN_ARG_SPLIT),function(arg){
arg.replace(FN_ARG,function(all,underscore,name){
$inject.push(name);
});
});
}
fn.$inject = $inject;
}
} else if (isArray(fn)) {
last = fn.length - 1;
assertArgFn(fn[last],'fn');
$inject = fn.slice(0,last);
} else {
assertArgFn(fn,'fn',true);
}
return $inject;
}
$inject = annotate(fn,serviceName),length,i,key;
key = $inject[i];
if (typeof key !== 'string') {
throw $injectorMinErr('itkn','Incorrect injection token! Expected service name as string,got {0}',key);
}
// locals优先
args.push(
locals && locals.hasOwnProperty(key)
? locals[key]
: getService(key)
);
}
if (isArray(fn)) {
fn = fn[length];
}
}
Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
instance = new Constructor();
// 调用invoke执行Type方法
returnedValue = invoke(Type,serviceName);
}