Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Provision Precendence in Dagger

When you use an @Inject-annotated constructor to inform Dagger how to provide a dependency, can you later override it in a Module? Case: my production code uses a component with the annotated constructor, and I want to override it with a test implementation during testing. Would my override = true Module successfully override the production implementation during testing?

Or a more general questions, what takes precedence, Modules or annotated classes?

like image 687
Dandre Allison Avatar asked Dec 18 '13 01:12

Dandre Allison


1 Answers

@Provides methods always trump @Inject Constructors and no-args Constructors (with field injection.

This is important, because an @Provides method is taking over responsibility for creation of the type, and that includes scoping, so a class marked @Singleton that is manually constructed in an @Provides method will not be scoped unless the @Provides method is scoped.

Note that you're using the word "override" in the context of testing... in this case, you don't need to use the @Module(override=true) setting (though there's no harm). It's just a precedence order, which resolves (in effect) as follows:

  1. @Module(overrides=true) @Provides methods
  2. @Module(overrides=false) (default) @Provides methods
  3. Just In Time binding of @Inject constructors
  4. Just In Time binding of no-arg constructors, IF class has @Inject fields.
like image 117
Christian Gruber Avatar answered Sep 30 '22 16:09

Christian Gruber