I have moduleA setup as an application wide singleton provider, ModuleB as a user related object provider
My user display fragment will use system wide bus to send message to others and use user related object to display.
Problem cannot inject different scrope class into one object. Use component.getX method works fine, but inject is prefered way. Error message: @UserScope may not reference bindings with difference scopes: @Provides @Singleton Bus ModuleA.provideBus()
@Module
public class ModuleA {
@Provides @Singleton Bus provideBus() {...}
}
Module B as user related Info provider
@Module
public class ModuleB{
private final User user;
public ModuleB(User user) {...}
@Provides @UserScope User provideUser() {}
@Provides @UserScope UserManager provideUserManager() {}
}
Components setup like following:
@Component (modules={ModuleA.class})
@Singleton
public interface ComponentA {
Bus getBus();
void inject(ClassA target);
}
@Component(modules={ModuleB.class})
@UserScope
public interface ComponentB {
User getUser();
UserManager getUserManager();
void inject(ClassA target);
}
class UserFragment exrtends Fragment {
@Inject Bus bus;
@Inject UserManager userManager;
public void onCreate() {
getComponentA().inject(this);
getComponentB().inject(this);
}
}
I think the main problem in your code snippets you provided, is that your
ModuleB
should have a dependency onModuleA
to correctly provide the singleton with the error you were getting. I.e. this should work:I recreated your classes and made some assumptions to fill in the blanks, and it seems to work fine. You can see the full working code here on GitHub. The only difference in my code is, what you called
ClassA
/UserFragment
I just calledMainActivity
but otherwise the structure is the same.Try this configuration, it works for me. There is really a lack of good documentation about Dagger2 so I studied a few open-source examples of code that you can find in GitHub etc by keyword like Dagger2.
Application level Component
Application level Module
Activity level Component
Activity level Module
Android Application class
And finally Activity