You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Dagger-Hilt注入Repository时无法创建ViewModel实例

Android Hilt注入ViewModel崩溃问题解决

问题描述

项目采用app -> feature -> data的模块分层结构,尝试通过Hilt向SignUpViewModel注入AuthRepository。已为ViewModel添加@HiltViewModel注解并使用@Inject标注构造函数,同时配置了AuthModule和DataStorageModule,但启动应用时崩溃,提示无法创建SignUpViewModel实例。尝试直接用@Provides提供实现类也未解决问题。

关键代码

SignUpViewModel

@HiltViewModel
class SignUpViewModel @Inject constructor(private val authRepository: AuthRepository) :
    ViewModel() {

    private val _signUpState = MutableStateFlow(RegistrationState())
    val signUpState = _signUpState.asStateFlow()

    fun onNameChange(name: String) {
        _signUpState.value = _signUpState.value.copy(name = name)
    }

    fun onEmailChange(email: String) {
        _signUpState.value = _signUpState.value.copy(email = email)
    }

    fun onPasswordChange(password: String) {
        _signUpState.value = _signUpState.value.copy(password = password)
    }

    fun onSignUpClick() {
        authRepository.registerUser()
    }
}

ViewModel创建代码

@Composable
fun SignUpScreen() {
    SignUpScreen(viewModel = hiltViewModel())
}

模块配置代码

@Module
@InstallIn(SingletonComponent::class)
abstract class AuthModule {
    @Binds
    internal abstract fun bindsAuthRepository(
        authRepository: AuthRepositoryImpl,
    ): AuthRepository
}

@Module
@InstallIn(SingletonComponent::class)
object DataStorageModule {
    @Provides
    @Singleton
    fun provideAuthLocalDataSource(@ApplicationContext context: Context): AuthDataStorage {
        return AuthDataStorage(context)
    }
}

崩溃信息

启动应用时触发崩溃,核心提示:

Cannot create an instance of class com.example.auth_feature.presentation.SignUpViewModel

完整崩溃日志(关键部分翻译)

java.lang.RuntimeException: 无法创建ru.yangel.auth_feature.presentation.SignUpViewModel实例
    ...
Caused by: java.lang.NoSuchMethodException: ru.yangel.auth_feature.presentation.SignUpViewModel.<init> []
    at java.lang.Class.getConstructor0(Class.java:3325)
    at java.lang.Class.getDeclaredConstructor(Class.java:3063)
    at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.kt:199)
    ... 76 more

排查与解决方案

1. 检查Application类配置

确保项目的Application类添加了@HiltAndroidApp注解,这是Hilt初始化的核心入口:

@HiltAndroidApp
class MyApp : Application() {
    // ...
}

2. 验证多模块Hilt依赖配置

  • feature模块的build.gradle.kts需添加Hilt相关依赖:
plugins {
    id("com.android.library")
    id("kotlin-android")
    id("kotlin-kapt")
    id("dagger.hilt.android.plugin")
}

dependencies {
    implementation("com.google.dagger:hilt-android:2.48")
    kapt("com.google.dagger:hilt-android-compiler:2.48")
    implementation("androidx.hilt:hilt-navigation-compose:1.1.0")
    // 其他依赖...
}
  • app模块需确保依赖feature模块,且自身Hilt配置正确。

3. 检查AuthRepositoryImpl的可注入性

AuthModule中使用@Binds绑定接口与实现类,要求AuthRepositoryImpl必须有@Inject标注的构造函数:

class AuthRepositoryImpl @Inject constructor(
    private val authDataStorage: AuthDataStorage
) : AuthRepository {
    // ...实现方法
}

4. 清理编译缓存并重建项目

执行Android Studio的File > Invalidate Caches... > Invalidate and Restart,清理编译缓存后重新构建项目,避免Hilt生成的代码未更新导致的问题。

5. 验证组件安装范围

若feature模块是独立模块,可尝试将AuthModule的@InstallIn改为ViewModelComponent::class,确保ViewModel能获取到依赖:

@Module
@InstallIn(ViewModelComponent::class)
abstract class AuthModule {
    @Binds
    internal abstract fun bindsAuthRepository(
        authRepository: AuthRepositoryImpl,
    ): AuthRepository
}

内容的提问来源于stack exchange,提问作者Rendivy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 09:45:53