Reputation: 565
How can I model circular dependency using dagger2? Lets say we have only two classes. First injection is via constructor and second is via method as in example below:
class A{
private B b;
@Inject
public A(B b)
{
this.b = b;
}
}
class B{
private A a;
@Inject
public B() { }
@Inject
public void injectA(A a)
{
this.a = a;
}
}
Upvotes: 0
Views: 83
Reputation: 5052
You can use lazy injection:
class B{
private Lazy<A> a;
@Inject
public B(Lazy<A> a) {
this.a = a;
}
}
Alternatively you can inject Provider<A>
, but be aware that provider returns new instance of A each time Provider::get
is invoked (assuming default scope), while Lazy::get
returns the same instance.
Upvotes: 2
Reputation: 93599
Inject a Provider<A>
or Provider<B>
into one of them instead of an A or B directly. Then as long as the two classes don't both need the other in the constructor it will work. If they both need each other in their constructors, then there's no way to do it.
Upvotes: 1
Reputation: 75376
To my knowledge you can’t.
Dependencies like this indicate that A and B might be tighter than they should be. Either merge them or refactor out the common part in C
Upvotes: 0