Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit fbcb7fd

Browse files
committed
fix($injector): circular dependency instatiation
1 parent fa69d10 commit fbcb7fd

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/Injector.js

+6-1
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,8 @@ function inferInjectionArgs(fn) {
273273

274274

275275
function createInjector(modulesToLoad) {
276-
var providerSuffix = 'Provider',
276+
var INSTANTIATING = {},
277+
providerSuffix = 'Provider',
277278
path = [],
278279
loadedModules = new HashMap(),
279280
providerCache = {
@@ -394,10 +395,14 @@ function createInjector(modulesToLoad) {
394395
throw Error('Service name expected');
395396
}
396397
if (cache.hasOwnProperty(serviceName)) {
398+
if (cache[serviceName] === INSTANTIATING) {
399+
throw Error('Circular dependency: ' + path.join(' <- '));
400+
}
397401
return cache[serviceName];
398402
} else {
399403
try {
400404
path.unshift(serviceName);
405+
cache[serviceName] = INSTANTIATING;
401406
return cache[serviceName] = factory(serviceName);
402407
} finally {
403408
path.shift();

test/InjectorSpec.js

+21
Original file line numberDiff line numberDiff line change
@@ -483,6 +483,27 @@ describe('injector', function() {
483483
createInjector([['$injector', myModule]]);
484484
}).toThrow('Unknown provider: $injector from ' + myModule);
485485
});
486+
487+
488+
it('should throw error when trying to inject oneself', function() {
489+
expect(function() {
490+
createInjector([function($provide){
491+
$provide.factory('service', function(service){});
492+
return function(service) {}
493+
}])
494+
}).toThrow('Circular dependency: service');
495+
});
496+
497+
498+
it('should throw error when trying to inject circular dependency', function() {
499+
expect(function() {
500+
createInjector([function($provide){
501+
$provide.factory('a', function(b){});
502+
$provide.factory('b', function(a){});
503+
return function(a) {}
504+
}])
505+
}).toThrow('Circular dependency: b <- a');
506+
});
486507
});
487508
});
488509

0 commit comments

Comments
 (0)