Dagger 2 inject method

最后都变了- 提交于 2019-12-07 14:26:37

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/31961094/dagger-2-inject-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!