Android Kotlin中Dagger/Hilt MissingBinding错误排查求助
Dagger/Hilt MissingBinding 错误排查与解决
错误日志
C:\XXXXX\AndroidLearning\MyTest\app\build\generated\hilt\component_sources\debug\com\example\mytest\MyTest_HiltComponents.java:125: error: [Dagger/MissingBinding] com.example.mytest.MyTestInjectionClass cannot be provided without an @Inject constructor or an @Provides-annotated method. public abstract static class SingletonC implements MyTest_GeneratedInjector, ^ com.example.mytest.MyTestInjectionClass is injected at com.example.mytest.MyViewModel(myTestInjectionClass) com.example.mytest.MyViewModel is injected at com.example.mytest.MyViewModel_HiltModules.BindsModule.binds(arg0) @dagger.hilt.android.internal.lifecycle.HiltViewModelMap java.util.Map<java.lang.String,javax.inject.Provider<androidx.lifecycle.ViewModel>> is requested at dagger.hilt.android.internal.lifecycle.HiltViewModelFactory.ViewModelFactoriesEntryPoint.getHiltViewModelMap() [com.example.mytest.MyTest_HiltComponents.SingletonC ? com.example.mytest.MyTest_HiltComponents.ActivityRetainedC ? com.example.mytest.MyTest_HiltComponents.ViewModelC]
已做操作
- ViewModel已添加
@HiltViewModel注解,构造器标注@Inject - 为
MyTestInjectionClass创建了Module,提供方法标注@Provides和@Singleton
可能的原因及解决方法
1. Module未添加必要注解
Hilt需要明确识别模块及其安装的组件范围,检查你的Module类:
// 正确示例 @Module @InstallIn(SingletonComponent::class) object MyTestInjectionModule { @Provides @Singleton fun provideMyTestInjectionClass(): MyTestInjectionClass { return MyTestInjectionClass() } }
- 必须给Module类添加
@Module注解,声明这是Hilt模块 @InstallIn(SingletonComponent::class)要和@Singleton作用域匹配,确保模块被安装到对应生命周期的组件中
2. 作用域与组件不匹配
如果@Provides方法用了@Singleton,但Module安装到了ActivityComponent等非单例组件,会导致作用域冲突。对应关系要准确:
@Singleton→SingletonComponent::class@ActivityScoped→ActivityComponent::class@ViewModelScoped→ViewModelComponent::class
3. 注入对象存在构造器冲突
如果MyTestInjectionClass本身有@Inject构造器,同时Module中又提供了@Provides方法,Hilt会无法确定注入来源。此时二选一即可:要么去掉类的@Inject构造器,要么删除Module中的提供方法。
4. Hilt依赖或插件配置错误
检查app/build.gradle中的配置是否完整:
// 顶部插件声明 plugins { id 'com.android.application' id 'org.jetbrains.kotlin.android' 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-lifecycle-viewmodel:1.0.0-alpha03" kapt "androidx.hilt:hilt-compiler:1.0.0" }
确保插件和依赖版本匹配,且kapt注解处理器配置正确。
5. 清理缓存重建项目
缓存异常可能导致Hilt生成的代码出错,执行以下操作:
- 点击Android Studio菜单栏
Build -> Clean Project - 再执行
Build -> Rebuild Project - 或直接删除项目根目录下的
build文件夹后重新构建
内容的提问来源于stack exchange,提问作者Nazir
相关产品推荐
相关产品推荐

