2

For example:

class A{
  B b;
  C c;
  @Inject
  A(B b){
    this.b = b;
  }
  @Inject
  A(C c){
    this.c = c;
  }
}

And in one of the module:

@Module
public class BModule {

private final B b;
public BModule(B b){
    this.b = b;
}

@Provides
BInterface provideB(){
    return b;
}
}

But I got error that I can't inject two constructors in a class, what should I do to handle the problem? Thank you!

LunarS
  • 95
  • 2
  • 10

1 Answers1

2

Classes are only ever constructed once; two constructors would never both be called on the same instance, so having two constructors annotated @Inject means that Dagger would have to pick one. What behavior are you trying to accomplish with those two annotated constructors?

Ideally, combine the constructors.

@Inject
A(B b, C c){
  this.b = b;
  this.c = c;
}

Or switch one to method injection if absolutely necessary:

@Inject
A(B b){
  this.b = b;
}
@Inject
void initialize(C c){ // Dagger calls this automatically
  this.c = c;
}
Community
  • 1
  • 1
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
  • my real problem is, I try to build Presenter with the instance of View and Model, however, since, Model can't be initialized without View itself. So it's more like a paradox. Finally I give up and only implement dagger between Presenter and View. Please inform me if you have better solution to this practice, thank you! – LunarS Jan 09 '17 at 22:37
  • 1
    Ah, yes, that requires a very different answer than the question you appeared to ask above. Bear in mind that you'd have equal trouble constructing this type of circular dependency by hand! Dagger added a feature that helps, though: You can [_inject a `Provider` or `Provider` instead_](https://groups.google.com/forum/#!topic/dagger-discuss/KRDGFD3rUGQ) with no additional bindings or configuration needed (per the ["Bindings in the graph" section of the Dagger 2 User's Guide](https://google.github.io/dagger/users-guide.html#bindings-in-the-graph)). – Jeff Bowman Jan 09 '17 at 23:20