Dagger 2 - 组件取决于两个组件

时间:2017-07-11 20:49:54

标签: dagger-2

问题:如何使用Dagger 2基于BeansComponentWaterComponent中的依赖关系构建CoffeeComponent?

ApplicationComponent <- @modules = Earth.module | | BeansComponent WaterComponent \ / CoffeeComponent

要求: BeansComponentWaterComponent具有单独的范围。

到目前为止

解决方案

BeansComponent将是ApplicationComponent

的子组件

WaterComponent将是ApplicationComponent

的子组件

ApplicationComponent使用EarthModule

WaterComponentBeansComponent使用ApplicationComponent (EarthModule)

中的相关性

可以在BeansComponent中将WaterComponentWaterBeansComponent的所有模块包含在一起,并创建CoffeeComponent作为WaterBeansComponent的子组件。但是这种方式不可能有不同的范围。

1 个答案:

答案 0 :(得分:1)

Dagger 2不支持以图中所示的方式混合示波器。有关原因的解释,请参阅this question

此外,如果你正确构建你的应用程序,你不应该需要范围多重继承。范围和组件跟踪生命周期,因此对于跟踪两个兄弟生命周期的子组件没有多大意义。

使用模块可能更好地实现您正在寻找的关注点分离。首先使用模块按功能分组。然后推断将在模块中绑定的依赖项的生命周期,并使用这些知识从模块中组合组件。