Dagger2 组件依赖于多个作用域组件

Dagger2 Component depends on more than one scoped component

嘿,我有三个组成部分:

有时我想在我的 ViewModel 中使用多个组件 - 但我 运行 出现异常,我可能不会 .inject(ViewModel) 与许多组件相同 class。

UserViewModel{
   @Inject ApiService api;
   @Inject DatabaseService db;

   public User(){
     Application.getApiComponent.inject(this)
     Application.getDBComponent.inject(this)
  }

}

因为我想解耦组件(用于测试目的) 我决定向我的 ApplicationComponent 添加依赖项,并在注入应用程序时能够使用 albo DB 和 REST

@PerApplication
@Component(dependencies = {DBComponent.class, RestApiComponent.class},
        modules = {ApplicationModule.class})
public interface ApplicationComponent{...}

@DbScope
@Component(modules = {DBModule.class})
public interface DBComponent {...}

@RestScope
@Component(modules = {RestApiRetrofitModule.class})
public interface RestApiComponent {...}

这次我运行编译进入ERROR:

PerApplication ApplicationComponent 依赖于多个作用域组件: @DbScope 数据库组件 @RestScope RestApiComponent

问题是当人们使用不止一种依赖项时,我没有找到任何示例 - 它是否受到限制? 当我删除 DBComponent 的 @Scope 时没问题 - 但我有无范围的实例,每次新实例时都会 return 当我从依赖项中删除一个组件时,我也将毫无错误地构建。

如何在我的组件中使用两个依赖项?

您快完成了 - dependencies = 需要进入依赖(子)组件

@PerApplication
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent{...}

@DbScope
@Component(dependencies = ApplicationComponent.class, modules = DBModule.class)
public interface DBComponent {...}

@RestScope
@Component(dependencies = ApplicationComponent.class, modules = RestApiRetrofitModule.class)
public interface RestApiComponent {...}

现在只需确保公开绑定在 ApplicationComponent 模块集中的依赖项,以便依赖组件可以使用它们。

因此,如果您在 ApplicationComponent 级别绑定 SharedPreferences,并且您希望该依赖与依赖组件共享,您将需要在 ApplicationComponent

@Component
public interface ApplicationComponent { 

    SharedPreferences exposeSharedPreferences();  
}

另外,您可能想重新考虑只为 DB 和 REST 创建作用域——这些更像是功能分组,您想要的解耦可以通过模块来实现。

您通常只需要 Android 应用程序中的几个作用域 - @PerApp@PerActivity 作用域,因为作用域跟踪生命周期,而这是两个主要的生命周期。