Dagger组件&子

时间:2017-10-22 05:38:02

标签: android dagger

我想弄清楚如何使用Dagger组件/子组件。我知道这是旧式的东西,但我有一个使用这个Dagger结构的遗留应用程序,我正在使用这个示例项目来更好地理解它。

此示例应用程序只有AppComponent,AppModule,ActivityComponent和ActivityModule。我正在尝试将MainActivityDependency注入到我的MainActivity中,但编译器说它可以在没有显式的@Provides的情况下提供它。但我已经明确提供了它。我知道我可以使用@Inject注释该类,但为了练习,我需要使用@Provides方法。

似乎我的依赖结构正确但无法弄明白。我已粘贴下面的示例代码,但这里也是github链接:

https://github.com/fkruege/daggerSubComponentPractice/tree/master/app/src/main/java/com/franctan/daggerpractice

谢谢

AppComponent.java
@Singleton
@Component(modules = AppModule.class)
public interface AppComponent {
    ActivityComponent.Builder activityComponentBuilder();
    Application application();
    void inject(MyApp myApp);
}

AppModule

@Module(subcomponents = {ActivityComponent.class})
public class AppModule {

    private Application app;

    public AppModule(Application app) {
        this.app = app;
    }

    @Provides
    @Singleton
    public Application provideApplication() {
        return app;
    }

    @Provides
    @Singleton
    public AppDependency provideAppDependency() {
        return new AppDependency();
    }

}

ActivityComponent

@ActivityScope
@Subcomponent(modules = ActivityModule.class)
public interface ActivityComponent {

    @Subcomponent.Builder
    interface Builder {
        Builder activityModule(ActivityModule module);
        ActivityComponent build();
    }

    void inject(MainActivity mainActivity);
}

ActivityModule

@Module

public class ActivityModule {

    private Activity activity;

    public ActivityModule(Activity activity) {
        this.activity = activity;
    }

    @ActivityScope
    @Provides
    public Activity provideActivity() {
        return activity;
    }

    @ActivityScope
    @Provides
    public MainActivityDependency provideMainActivityDependency() {
        return new MainActivityDependency();
    }


}

MyApp

public class MyApp extends Application {

    public AppComponent appComponent;

    @Inject
    AppDependency appDependency;

    @Override
    public void onCreate() {
        super.onCreate();
        appComponent = DaggerAppComponent
                .builder()
                .appModule(new AppModule(this))
                .build();

        appComponent.inject(this);
    }
}

MainActivity

 @Inject
    MainActivityDependency mainActivityDependency;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        MyApp myApp = (MyApp) getApplication();

        myApp.appComponent
                .activityComponentBuilder()
                .activityModule(new ActivityModule(this))
                .build()
                .inject(this);

1 个答案:

答案 0 :(得分:0)

所以想通了。事实证明,ActivityScope界面定义不正确:

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Scope
public @interface ActivityScope {
}

@Qualifier注释搞砸了。愚蠢的错误。