Jacques Giraudel
Jacques Giraudel

Reputation: 512

With Dagger 2, is it possible to inject on a same class from different subcomponents or from different components?

It seems to be impossible but I can't find it written explicitly. Is there a clear reason for that ?

Thanks

Upvotes: 3

Views: 472

Answers (2)

David Medenjak
David Medenjak

Reputation: 34532

That's not possible. A component can either inject everything at once or the compilation will fail with a cannot be provided error, listing what it's missing.

After all you can't partially call a constructor (if using constructor injection) and also partially injecting fields would be rather indeterministic about which objects were injected when, how, or with which scope. If both components could supply a dependency, which should provide it? Do you create and inject the object twice? What if another object depends on it in the other component? It would create more confusion than any good it could do and provide a source for a lot of errors and unexpected behavior.

Upvotes: 3

Benjamin
Benjamin

Reputation: 7368

Only one component can be used to inject inside a given class. You can have several subcomponents dependencies installed on it though.

Upvotes: 0

Related Questions