Skip to content
This repository has been archived by the owner on Dec 6, 2017. It is now read-only.

Should be able through injector instantiate a class that depends on the class being instantiated #5

Closed
pavelgj opened this issue Jul 8, 2013 · 2 comments

Comments

@pavelgj
Copy link
Contributor

pavelgj commented Jul 8, 2013

class ParentDynamicallyInstantiatingChild {
  ParentDynamicallyInstantiatingChild(Injector injector) {
    injector.get(ChildDependingOnParent);
  }
}

class ChildDependingOnParent {
  ChildDependingOnParent(ParentDynamicallyInstantiatingChild _);
}

it('should be able through injector instantiate a class that depends on the class being instantiated', () {
  var injector = new Injector();
  expect(() {
    injector.get(ParentDynamicallyInstantiatingChild);
  }, not(throwsA(anything)));
});

throws
Cannot resolve a circular dependency! (resolving ParentDynamicallyInstantiatingChild -> ChildDependingOnParent -> ParentDynamicallyInstantiatingChild)

@pavelgj
Copy link
Contributor Author

pavelgj commented Jul 8, 2013

I think I want to withdraw this one... it is a circular dependency, instantiation of ParentDynamicallyInstantiatingChild is not complete at that point.

@vojtajina
Copy link
Contributor

Well, this IS a circular dependency.

In general, I think we should try to avoid it, often it's possible http://misko.hevery.com/2008/08/01/circular-dependency-in-constructors-and-dependency-injection/

Workaround can be using a setter:

  • A depends on B, B depends on A
  • we make A on B dependency "setter" (instead of passed into the constructor)
module.factory('B', (A a) {
  var b = new B(a);

  // set manually the back-ref
  a.b = b;

  return b;
});

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

No branches or pull requests

2 participants