Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Dagger Modules with constructor arguments?

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?

like image 773
thebamaman Avatar asked Apr 06 '13 02:04


2 Answers

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

like image 45
Jörg Avatar answered Sep 27 '22 19:09


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:

public class ContextModule {

    private final Context mContext;

    public ContextModule(Context context) {
        mContext = context;

    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 {

    public LocationManager provideLocationManager(Context context) {

        return (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    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.

like image 144
Marco RS Avatar answered Sep 27 '22 20:09

Marco RS