我目前正在尝试找出 Dagger 2。我正在尝试设置 4 个范围:App、User、Activity、Fragment。用户和活动组件是应用程序的子组件。 Fragment是一个以Activity为依赖的组件。
假设我的 UserSettingsActivity 需要一个工具栏(由 ActivityModule 提供)和一个 UserProfile(由 UserModule 提供)。在我从数据库中请求之前,我不会获得用户配置文件,而工具栏可以立即提供。因此注入的顺序是首先注入 ActivityComponent,然后注入 UserComponent。我有 2 个 @Inject 字段,一个用于工具栏,一个用于活动中的 UserProfile。我希望 dagger 知道依赖项来自不同的模块,但它似乎抱怨注入到 ActivityComponent 时无法提供 UserProfile。显然ActivityModule不能提供,但是为什么它没有连接UserModule提供的UserProfile呢?
据我所知,Dagger-2 不支持“部分注入”。
因此,当您致电myComponent.inject(this)
, 如果出现以下情况,Dagger-2 会抛出错误myComponent
无法提供全部@Inject
带注释的成员this
.
我发现有两种方法可以解决此限制:
- Remove
@Inject
注释来自UserProfile
, 暴露UserProfile
通过公共方法UserComponent
并在以下情况下手动注入UserComponent
已准备好使用。与此类似的东西:userProfile = userComponent.getUserProfile()
- 不要做
UserComponent
依赖于数据获取。UserComponent
可以用来注入Toolbar
还有一些UserProfileProvider
同时,你会获取UserProfile
from UserProfileProvider
当它可用时。
我个人认为第二种方法是更好的选择。应使用 DI 库来满足构造时对象的依赖性。在Android中我们无法构建Activity
or Fragment
我们自己,因此我们执行 DIonCreate()
, onAttach()
, onCreateView()
等等,但这并不意味着我们应该使用 DI 库来帮助控制应用程序的流程。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)