Dagger2:使父组件依赖项对子作用域组件可访问

4

我有如下设置:

@ApplicationScope
@Component(
        dependencies = {AppContextComponent.class, CertUtilsComponent.class, ServiceComponent.class, JobManagerComponent.class})
public interface ApplicationComponent
        extends AppContextComponent, CertUtilsComponent, ServiceComponent, JobManagerComponent {

    void inject(MainActivity mainActivity); //honestly, I won't need this
}

我有一个以下的子组件:

@PresenterScope
@Component(dependencies = {ApplicationComponent.class, PersistenceComponent.class})
public interface PresenterComponent
        extends ApplicationComponent, PersistenceComponent {
    void inject(HomePresenter homePresenter);

    void inject(SendCertificateRequestInteractor sendCertificateRequestInteractor);
}

问题在于 PersistenceComponent 有以下组件作为其依赖项:
@Component(dependencies = {JobManagerComponent.class, RealmComponent.class, RepositoryComponent.class}, modules = {PersisterModule.class})
public interface PersisterComponent {
    DummyCertPersister dummyCertPersister();
}

这里使用了JobManagerComponent,它是ApplicationComponent的依赖项。

不幸的是,这个组件似乎没有从ApplicationComponent继承。我需要明确跟踪这个组件,并像这样为生成器提供它。

//INJECTOR
    ApplicationComponent applicationComponent = DaggerApplicationComponent.builder()
            .appContextComponent(appContextComponent)
            .certUtilsComponent(certUtilsComponent)
            .jobManagerComponent(jobManagerComponent)
            .serviceComponent(serviceComponent)
            .build();

    this.jobManagerComponent = jobManagerComponent;
    this.applicationComponent = applicationComponent;
    this.certUtilsComponent = certUtilsComponent;
    this.appContextComponent = appContextComponent;
    this.serviceComponent = serviceComponent;
}

public ApplicationComponent getApplicationComponent() {
    return applicationComponent;
}

public JobManagerComponent getJobManagerComponent() {
    return jobManagerComponent;
}

当我构建持久化组件时,通过getter提供此功能:

    PersisterComponent persisterComponent = DaggerPersisterComponent.builder()
            .jobManagerComponent(Injector.INSTANCE.getJobManagerComponent()) //this should be subcomponent
            .realmComponent(realmComponent)
            .repositoryComponent(repositoryComponent)
            .persisterModule(new PersisterModule())
            .build();

我希望 JobManagerComponent 继承自 ApplicationComponent,由于涉及it技术,我猜想需要将其转为 @Subcomponent 并提供一个方法,但目前来看并没有成功(我没有得到 builder 方法,但仍然看不到在 JobManagerComponent 中的 jobManager)。

使用 @Subcomponent 可以实现吗?或者我是否需要跟踪 ApplicationComponent 的“子组件”,以防子组件依赖它?

哦...等我有时间了再回答这个问题。 - EpicPandaForce
1个回答

4
答案是,我对Dagger2中组件的工作方式的概念理解错误了。
一个组件只有在它子范围内时才应该依赖于另一个组件。如果一个组件有多个组件依赖,则不能依赖于具有作用域的组件;这意味着它们不能使用作用域,也不能使用具有作用域的模块。除非模块保留对新实例的引用,否则每次注入都会得到一个新实例。这很糟糕,不是你想要的结果。
正确的方法是将相同作用域的每个模块绑定到同一组件上。这样,提供的依赖项可以在构造函数中访问,并且您不会在不同组件之间共享相同的模块时出现问题。
因此,问题中的方法是完全错误的。 请使用此方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接