android - Dagger2 子组件模块覆盖

标签 android dependency-injection dagger-2

ApplicationComponent.java

@Component(modules = SomeModule.class)
@ApplicationScope
public interface ApplicationComponent {
    // stuff
    ActivityComponent activityComponent();
}

ActivityComponent.java

@Subcomponent(modules = AnotherModule.class)
@ActivityScope
public interface ActivityComponent {
    // stuff
    void inject(MainActivity mainActivity);
}

SomeModule 可以使用 this 之类的内容进行覆盖。但是AnotherModule怎么样?

一种解决方案是将这两个组件分开,但是如果我想重用父组件中的一些绑定(bind)该怎么办?

编辑:

MainActivity.java

onCreate(Bundle bundle) {
    getApplicationComponent().getActivityComponent().inject(this);
}

编辑2:

ActivityRyle.java

init() {
    application.setComponent(DaggerApplicationComponent.builder()
                    .someModule(new TestSomeModule(application))
                    .build();
}

edit3:我试图避免在Application(创建主要组件的地方)中连接太多东西。

最佳答案

您也只需覆盖该模块即可。

请记住您创建子组件的方式:

public interface ApplicationComponent {

    ActivityComponent activityComponent(/*needed modules go here*/);
}

因此,除非模块有无参数构造函数,否则必须将它们作为参数放在方法声明中。

如果您希望能够使用无参数构造函数覆盖模块,则必须将它们添加到方法签名中:

public interface ApplicationComponent {

    ActivityComponent activityComponent(AnotherModule module);
}

在您的测试中,您只需提供您的子类。

关于android - Dagger2 子组件模块覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37489856/

相关文章:

单击 ListView 项时,Android- Activity 组不会启动新 Activity

android - 在整洁的架构中将依赖注入(inject)类放在哪里

dependency-injection - 如何正确地将 ObjectManager 注入(inject)到 Fieldsets 中?

java - 带有 Kotlin 的 Dagger 2,在 ApplicationComponent 中返回具有泛型的类型

java - Dagger2 如何基于java类进行注入(inject)?

java - 空点异常 - ImageLoader

Android Studio 刷新布局无需重建项目

java - setSupportActionBar(toolbar) 即使导入 android.support.v7.widget.Toolbar 后也会出现运行时错误

c# - 如何验证 ASP.NET Core 中的 DI 容器?

android - Kotlin 缺少提供程序的 Dagger 2 错误