gpt4 book ai didi

dagger-2 - 使子组件继承不同组件的依赖关系

转载 作者:行者123 更新时间:2023-12-02 03:12:58 25 4
gpt4 key购买 nike

最近我一直在使用 Dagger 2 进行大量工作,但我有一个特殊的用例,由于不同的原因我无法按照我想要的方式进行操作:1)不可能; 2) 我只是不理解作用域和组件/子组件背后的概念。

我有 3 个组件:AppComponent、DBComponent、ActivityComponent。

我需要让我的事件继承 AppComponent 和 DBComponent 的依赖项。这是我的以下设置:

应用组件:

@Singleton
@Component(modules = { AppModule.class }) {
EventBus bus()
ActivityComponent plus(ActivityModule activityModule);
}

数据库组件:

@Database
@Component(dependencies = AppComponent.class, modules = DatabaseModule.class) {
ActivityDependency activityDependency();
}

事件组件:

@PerActivity
@Subcomponent(modules = ActivityModule.class) {
void inject(MainActivity activity);
}

当我注入(inject) bus() 时,一切正常,但当我尝试注入(inject) ActivityDependency() 时,它根本不起作用。我想不通为什么...

请注意:我已经阅读了这里和外部几乎所有解释作用域、组件和子组件的帖子,但我仍然无法理解如何实现我想要的。

注意 2:我知道解决此问题的一种方法是将 DatabaseModule.class 作为模块添加到 AppComponent 中,并从等式中删除 DatabaseComponent。但我觉得这会使 AppComponent 包含太多信息,而这并不是真正可行的方法。

最佳答案

inherit dependencies from AppComponent and DBComponent.

错了。你需要继承AppComponent的依赖,DBComponent的内容应该是AppComponent的一个模块。

Note 2: I know one way to fix this which is to add DatabaseModule.class as a module in the AppComponent and remove DatabaseComponent from the equation. But I feel this will make AppComponent with too much information and this is not really the go to way.

是的,如果您使用作用域依赖项,这是首选方法。


把依赖继承想成Java中的extends关键字。

不能用同一个类扩展多个类,对吗?

同样,您也不能扩展多个作用域的组件。

因此,如果您希望图形为给定范围提供绑定(bind),那么您的组件需要具有该给定范围的所有模块。 @Database 并不是真正的范围(想想生命周期),它是重命名的 @Singleton

关于dagger-2 - 使子组件继承不同组件的依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38877294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com