In Guice, I had full control over when Modules were constructed, and used some Modules with constructor arguments that I installed.
In Dagger however, the method of referencing other Modules is through the @Module includes annotation, and doesn't present me with the same method of creating Modules to install.
Is it possible to create a sane ObjectGraph from multiple Modules that have constructor arguments? Especially one that will work with dagger-compiler, and not run into a cyclical graph?
ObjectGraph.create() takes a variable list of modules (Varargs) so you are able to do this:
ObjectGraph objectGraph = ObjectGraph.create(new ProductionModule(context), new OverridingTestModule());
Take a look at Dagger's InjectionTest.java (see test "moduleOverrides" there): https://github.com/square/dagger/blob/master/core/src/test/java/dagger/InjectionTest.java
If you have multiple modules with that use the same object then maybe you should separate that object into its own module. For example, a lot of the Modules use the Application context so I have the following module:
@Module
public class ContextModule {
private final Context mContext;
public ContextModule(Context context) {
mContext = context;
}
@Provides
public Context provideContext() {
return mContext;
}
}
So now in other modules when when I need a context object I just include the module.
For example:
@Module(entryPoints = { MyFragment.class }, includes = { ContextModule.class })
public class ServicesModule {
@Provides
public LocationManager provideLocationManager(Context context) {
return (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
@Provides
public Geocoder provideGeocoder(Context context) {
return new Geocoder(context);
}
}
Then when I construct the object graph I end up with only one module that takes the application context as its argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With