Question

I would really like to implement Dagger in my app but I have a hard time to understand how it should be configured correctly. I have two classes that I would like to inject.

public class LoginController {
    @Inject Bus bus;
    @Inject Context context;
    // more code 
}

public class LoginFragment {
    @Inject Bus bus;
    // more code
}

If I put all my code in one module it works fine:

@Module(injects = {LoginController.class, LoginFragment.class})
public class BasicModule {

    @Provides
    @Singleton
    public Bus busProvider() {
        return new Bus();
    }
    @Provides
    public Context provideContext() {
        return RblMobileApp.getContext();
    }
}

But when I put those methods in two different modules (BasicModule and TestModule) I get compiler errors:

@Module(injects = {LoginController.class, LoginFragment.class})
public class BasicModule {
    @Provides
    @Singleton
    public Bus busProvider() {
        return new Bus();
    }
}

Error:(18, 8) java: No injectable members on android.content.Context. Do you want to add an injectable constructor? required by rblmobile.controllers.LoginController for rblmobile.injection.BasicModule 

@Module(injects = {LoginController.class})
public class TestModule {
    @Provides
    public Context provideContext() {
        return RblMobileApp.getContext();
    }
}

Error:(13, 8) java: No injectable members on com.squareup.otto.Bus. Do you want to add an injectable constructor? required by rblmobile.controllers.LoginController for rblmobile.injection.TestModule

So basically I'm told that BasicModule doesn't deliever Context and TestModule doesn't deliever Bus. Why does the ObjectGraph not know that the respective Constructor is in the other module?

Thanks

EDIT: That's the method where the ObjectGraph gets created.

public static void init(final Object... modules) {
    Log.i(TAG, "initializing object graph");

    if (objectGraph == null) {
        objectGraph = ObjectGraph.create(modules);
    } else {
        objectGraph = objectGraph.plus(modules);
    }
}
Était-ce utile?

La solution

There is a @Module annotation attribute called complete. Try to set it to false:

@Module(complete = false, injects = {LoginController.class, LoginFragment.class})
public class BasicModule {
    @Provides
    @Singleton
    public Bus busProvider() {
        return new Bus();
    }
}

@Module(complete = false, injects = {LoginController.class})
public class TestModule {
    @Provides
    public Context provideContext() {
        return RblMobileApp.getContext();
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top