kotlin - 如果没有 @Provides 注释的方法 HILT,则无法提供用户
问题描述
我在应用程序中使用 Dagger Hilt 并且我有这个模块:
@InstallIn(ActivityComponent::class)
@Module
object MainActivityModule {
/**
Provides current user that is stored in an intent after Logged In
**/
@Provides
@CurrentUser
fun providesCurrentUser(
@ActivityContext activity: Context
): User {
val intent: Intent = (activity as MainActivity).intent
return intent.getSerializableExtra(CURRENT_USER) as User
}
}
然后我尝试User
像这样调用另一个模块:
@InstallIn(ViewModelComponent::class)
@Module
object RepositoryModule {
@Provides
fun providesActivityRepository(
@CurrentUser currentUser: User
): ActivityRepository {
return ActivityRepository(currentUser)
}
}
我收到一个错误:User cannot be provided without an @Provides-annotated method.
我是匕首新手,知道我做错了什么吗?
我试图改变@InstallIn(ViewModelComponent::class)
但@InstallIn(ActivityComponent::class)
相同
解决方案
与Hilt Component 层次结构中一样,ViewModelComponent 是 ActivityRetainedComponent 的子组件,ActivityRetainedComponent 是 SingletonComponent 的子组件。(“ActivityRetainedComponent
存在于配置更改中,因此它首先创建Activity#onCreate()
并在最后销毁Activity#onDestroy()
。”)因此,您RepositoryModule
应该安装在ActivityComponent
或者ActivityRetainedComponent
如果您希望它可以从MainActivityModule
您安装的ActivityComponent
.
由于您提到“我尝试更改@InstallIn(ViewModelComponent::class)
为@InstallIn(ActivityComponent::class)
但相同”,因此我建议发布完整且准确的错误消息:您的消息User cannot be provided without an @Provides-annotated method
可能表明您尝试在其他地方注入,而不是您在此处发布User
的合格。@CurrentUser User
推荐阅读
- java - 在 lambda forEach() 中处理多个列表
- c - 为什么我们需要在 C 中嵌套在结构中时声明联合类型的变量?
- node.js - 如何将结果限制为具有特定值的数组的字段?
- php - 按 Laravel PHP/MYSQL 中添加数字的最后日期递增唯一的 INVOICE 编号
- matlab - 在 matlab 中安装 matConvNet 的请求?
- python - 替换表达式中的值并对python格式中的替换值执行操作()
- javascript - Vanilla Javascript 与 jQuery 类似的语法
- node.js - 创建 jwt 验证模块时无法读取未定义的属性“标题”
- swiftui - 如何使用循环在 SwiftUI 中创建许多图像
- python - 在 Python 中使用正则表达式检查章节编号?