在Gradle模块中使用Dagger Multibinding

时间:2017-06-07 23:04:49

标签: android gradle dependency-injection guice dagger

Dagger 用户......我是不是想做一些不可能的事情?以下是我的应用的degraph生成的Gradle模块视图。

modular-android-app

想象一下,我的应用程序有一个导航抽屉。我希望根据通过多重绑定填充的集合添加抽屉中的列表项。这种多重绑定的贡献者是> 1 Gradle模块。 例如,从user模块添加名为“帐户”的列表项,从legal模块添加名为“条款和条件”的第2项,并添加“搜索”导航条目来自search Gradle模块。这些模块可以被视为独立应用程序,捆绑在一起形成完整的应用程序体验。它们可以单独运行。

关于这个的Dagger文档看起来像是Guice的复制粘贴,但有一个很大的复杂功能。它说明了;

  

“Dagger允许您将多个对象绑定到集合中,即使是   使用多绑定将对象绑定在不同的模块中。 “

......但这意味着Dagger @Modules,对吧?是否可以跨Gradle模块填充多重绑定?我尝试过类似于此的东西,这不是我的预期(并非所有贡献都被收集);

家长应用

@Module
abstract class PluginModule {
  @Multibinds @NavigationContribution abstract Set<NavigationEntry> navigables();
}

legal Gradle模块包含Dagger @Module

@Module
class LegalModule {
  @Provides
  @NavigationContribution 
  @IntoSet
  static NavigationEntry provideLegalNavigation() {
    return ...;
  }
}

user Gradle模块包含Dagger @Module

@Module
class AccountModule {
  @Provides
  @NavigationContribution 
  @IntoSet
  static NavigationEntry provideAccountNavigation() {
    return ...;
  }
}

在运行应用程序时,只有应用程序“上下文”下的贡献可以在调用时使用;

@Inject @NavigationContribution Set<NavigationEntry> navigationEntries();

可以访问其他贡献,但可以通过获取子Gradle模块的dagger.Component并显示一个方法来获取条目来“手动”访问。

这违背了我的应用程序的multibinder的目的。这可能吗?如果没有,为什么?

更新:与杰夫分道

enter image description here

因此,顶级模块注释看起来像这样;

@ApplicationLifecycle
@Component(
    modules = {
        OceanLifeModule.class,
        AddSpotActivityModule.class,
        ModelModule.class,
        PluginModule.class
    },
    dependencies = {
        NavigationComponent.class,
        LegalComponent.class,
        PreferenceComponent.class,
        DomainComponent.class
    }
)

1 个答案:

答案 0 :(得分:1)

@ jeff-bowman - 我在这里失踪的是includes = {}上的PluginModule。 Zac Sweers关于同一主题here的博客文章指出了我正确的方向。