Android ViewModel依赖注入报错:无法创建LoginViewModel实例
Hilt依赖注入下LoginViewModel实例化失败问题排查
开发Android应用时,使用Hilt做依赖注入,编写的LoginViewModel在移除构造函数的AuthRepository参数时能正常实例化,但添加该参数后报错:Cannot create an instance of class newjeans.bunnies.auth.viewmodel.LoginViewModel。
相关代码
LoginViewModel代码
@HiltViewModel class LoginViewModel @Inject constructor(private val authRepository: AuthRepository) : ViewModel() { private val _hidePassword = MutableLiveData(false) val hidePassword: LiveData<Boolean> get() = _hidePassword private val _autoLogin = MutableLiveData(false) val autoLogin: LiveData<Boolean> get() = _autoLogin private val _loginError = MutableLiveData(false) val loginError: LiveData<Boolean> get() = _loginError fun login(userId: String, password: String) { viewModelScope.launch { kotlin.runCatching { authRepository.login( LoginReqeustDto( userId = userId, password = password ) ) }.onSuccess { // val prefs = NewJeansBunniesApplication.prefs // prefs.accessToken = it.accessToken // prefs.autoLogin = autoLogin.value?:false // if(autoLogin.value == true) // prefs.refreshToken = it.refreshToken // _loginError.value = false }.onFailure { e -> _loginError.value = true Log.d("LoginViewModel", e.message.toString()) } } } fun loginError(status: Boolean) { _loginError.value = status } fun autoLogin(status: Boolean) { _autoLogin.value = status } fun hidePassword(status: Boolean) { _hidePassword.value = status } }
怀疑相关的代码片段
AuthApi接口
interface AuthApi { @POST("/api/auth/login") suspend fun login( @Body loginRequestDto: LoginReqeustDto ): LoginResponseDto @POST("/api/auth/signup") suspend fun signup( @Body signupRequestDto: SignupReqeustDto ): SignupResponseDto @PATCH("/api/auth") suspend fun refresh( @Header("refresh-token") token: String ) }
ApiRepositoryImpl实现类
class ApiRepositoryImpl @Inject constructor( private val authApi: AuthApi ) : AuthRepository { override suspend fun login(loginRequestDto: LoginReqeustDto): LoginResponseDto { return authApi.login(loginRequestDto) } override suspend fun signup(signupRequestDto: SignupReqeustDto): SignupResponseDto { return authApi.signup(signupRequestDto) } override suspend fun refresh(token: String) { return authApi.refresh(token) } }
AuthRepository接口
interface AuthRepository { suspend fun login(loginRequestDto: LoginReqeustDto): LoginResponseDto suspend fun signup(signupRequestDto: SignupReqeustDto): SignupResponseDto suspend fun refresh(token: String) }
RepositoryModel模块
@Module @InstallIn(SingletonComponent::class) class RepositoryModel { @Provides @Singleton fun provideAuthRepository(apiRepositoryImpl: ApiRepositoryImpl): AuthRepository = apiRepositoryImpl }
AuthApi提供方法
@Provides @Singleton fun provideAuthApi(retrofit: Retrofit): AuthApi = retrofit.create(AuthApi::class.java)
排查方向及解决方法
1. 补充Retrofit实例的注入逻辑
provideAuthApi依赖Retrofit实例,但当前代码未提供Retrofit的@Provides方法,Hilt无法自动创建Retrofit实例,导致AuthApi、ApiRepositoryImpl、AuthRepository的注入链断裂。
解决方法:添加Retrofit提供模块,示例如下:
@Module @InstallIn(SingletonComponent::class) object RetrofitModule { @Provides @Singleton fun provideRetrofit(): Retrofit { return Retrofit.Builder() .baseUrl("你的API基础地址") .addConverterFactory(GsonConverterFactory.create()) .build() } }
2. 检查Hilt基础配置是否完整
- 确保Application类添加
@HiltAndroidApp注解:
@HiltAndroidApp class NewJeansBunniesApplication : Application() { // 你的其他代码 }
- 确保承载ViewModel的Activity/Fragment添加
@AndroidEntryPoint注解,并使用hiltViewModel()(Fragment)或viewModels()(Activity)获取ViewModel实例:
@AndroidEntryPoint class LoginActivity : AppCompatActivity() { private val viewModel: LoginViewModel by viewModels() // 你的其他代码 }
3. 修正模块类名(可选但推荐)
当前模块类名为RepositoryModel,建议改为RepositoryModule,避免与数据模型类混淆,不影响功能但提升代码可读性。
4. 检查Hilt依赖是否齐全
确保模块级build.gradle中添加了完整的Hilt依赖:
plugins { id 'com.android.application' id 'com.google.dagger.hilt.android' id 'kotlin-kapt' } dependencies { implementation 'com.google.dagger:hilt-android:2.48' kapt 'com.google.dagger:hilt-android-compiler:2.48' implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03' kapt 'androidx.hilt:hilt-compiler:1.0.0' }
5. 清理缓存并重新构建
编译缓存可能导致Hilt生成代码异常,执行Build > Clean Project和Build > Rebuild Project,或使用命令行:
./gradlew clean build
内容的提问来源于stack exchange,提问作者HamTory
相关产品推荐
相关产品推荐

