Reputation: 22038
I'm playing around with Dagger 2.
I have the following Module
:
@Module
public class GameSetupModule {
@Provides
@Singleton
GameSetup provideGameSetup() {
return new GameSetup();
}
}
and the according Component
:
@Singleton
@Component(modules = {GameSetupModule.class})
public interface GameSetupComponent {
GameSetup provideGameSetup();
void inject(SetupActivity activity);
// void inject(Fragment fragment);
void inject(SetupCompletedFragment fragment);
void inject(SelectQuarterLengthFragment fragment);
void inject(SelectTeamColorsFragment fragment);
void inject(SelectUserRoleFragment fragment);
}
As you can see the GameSetup is to injected into several different Fragments like this:
@Inject
GameSetup gameSetup;
onCreate(){
getGameSetupComponent().inject(this);
}
It works fine when implemented as seen above, the injection does not work though when I just use a single method
void inject(Fragment fragment);
for all Fragments.
Am I doing something wrong or is this even intended to have more control over where the GameSetup
may be injected and where it may not be available?
Upvotes: 3
Views: 2970
Reputation: 81578
Dagger2 does not support base class injections out of the box.
A method such as void inject(Fragment fragment);
would only inject the fields that are specified with @Inject
within the Fragment
class, and not its subclasses.
According to jackhexen on Reddit, what you are doing is possible to do with reflection. But reflection can break Proguard.
I personally would vote for this solution.
Upvotes: 8