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

Commit

Permalink
fix($injector): circular dependency instatiation
Browse files Browse the repository at this point in the history
  • Loading branch information
mhevery committed Feb 22, 2012
1 parent fa69d10 commit fbcb7fd
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/Injector.js
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,8 @@ function inferInjectionArgs(fn) {


function createInjector(modulesToLoad) {
var providerSuffix = 'Provider',
var INSTANTIATING = {},
providerSuffix = 'Provider',
path = [],
loadedModules = new HashMap(),
providerCache = {
Expand Down Expand Up @@ -394,10 +395,14 @@ function createInjector(modulesToLoad) {
throw Error('Service name expected');
}
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] === INSTANTIATING) {
throw Error('Circular dependency: ' + path.join(' <- '));
}
return cache[serviceName];
} else {
try {
path.unshift(serviceName);
cache[serviceName] = INSTANTIATING;
return cache[serviceName] = factory(serviceName);
} finally {
path.shift();
Expand Down
21 changes: 21 additions & 0 deletions test/InjectorSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,27 @@ describe('injector', function() {
createInjector([['$injector', myModule]]);
}).toThrow('Unknown provider: $injector from ' + myModule);
});


it('should throw error when trying to inject oneself', function() {
expect(function() {
createInjector([function($provide){
$provide.factory('service', function(service){});
return function(service) {}
}])
}).toThrow('Circular dependency: service');
});


it('should throw error when trying to inject circular dependency', function() {
expect(function() {
createInjector([function($provide){
$provide.factory('a', function(b){});
$provide.factory('b', function(a){});
return function(a) {}
}])
}).toThrow('Circular dependency: b <- a');
});
});
});

Expand Down

0 comments on commit fbcb7fd

Please sign in to comment.