首页 > 解决方案 > 如果没有 @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)相同

标签: kotlindagger-2dagger-hilt

解决方案


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


推荐阅读