I'm trying to use Dagger to do Dependency Injection on an app that I'm building, and running into trouble constructing proper DAGs when I have one package's Module depending on values provided by the Injector (presumably provided by another Module).
If I have a simple module for some configurable variables (that I might want to swap out for testing environments, for example)
@Module(
injects = DependentModule.class,
)
public class ConfigModule {
@Provides @Named("ConfigOption") String provideConfigOption() {
return "This Module's configurable option!";
}
}
and another module depends on it, e.g.
@Module(
injects = {
TopLevelClass.class
}
)
public class DependentModule {
@Inject @Named("ConfigOption") String configOption;
public DependentModule() {
ObjectGraph.create(this).inject(this);
doSomethingWithConfig(configOption);
}
@Provides @Singleton UsefulValue provideUsefulValue() {
// Whatever this module needs to do...
}
}
The line where I try to bootstrap the injection in the constructor fails, and it complains that I haven't specified an explicit injects
line in a proper module.
Through trial-and-error I see this goes away if in @Module
I add a line include = ConfigModule.class
, but this strikes me as semantically wrong, since a) the DAG I'll be creating will now include the values of both modules, rather than just one, and b) it defeats the purpose/flexibility of DI in the first place to link a specific Module rather than simply let Dagger inject the appropriate value.
I'm presuming I shouldn't be creating an Object Graph with this
only to inject into it? But then I run into the issue of not linking a specific Module...
Succinctly:
- What is the 'proper' way to Inject values into one Modules that may be provided from other Modules? Here I'm using field injection, but my experiments with constructor injection have also resulted in a lot of failure.
- Relatedly, when is it appropriate to use
addsTo
vs.includes
?
Thanks :)