Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dagger 2 inject method

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?

like image 798
fweigl Avatar asked Feb 26 '26 16:02

fweigl


1 Answers

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.

like image 82
EpicPandaForce Avatar answered Mar 01 '26 07:03

EpicPandaForce