使用Hilt向ViewModel注入WeatherRepository时遇MissingBinding错误
Hilt注入WeatherRepository到ViewModel报错解决办法
错误信息
WeatherRepository cannot be provided without an @Provides-annotated method.
public abstract static class SingletonC implements WeatherApplication_GeneratedInjector
问题根源
你的WeatherModule使用了@InstallIn(ActivityComponent::class),但存在两个关键冲突:
- 标注
@Singleton的依赖必须挂载到SingletonComponent作用域下,Hilt才能将其作为全局单例管理 @HiltViewModel修饰的ViewModel依赖来自ViewModelComponent,它的作用域依赖于SingletonComponent,无法访问ActivityComponent层级的依赖
修复步骤
将WeatherModule的@InstallIn目标组件改为SingletonComponent::class,确保所有单例依赖都在全局作用域内提供:
修改后的WeatherModule代码:
@Module @InstallIn(SingletonComponent::class) // 替换原有的ActivityComponent object WeatherModule { @Provides @Singleton fun provideDatabase(@ApplicationContext context: Context): WeatherDatabase { return Room.databaseBuilder( context, WeatherDatabase::class.java, "WeatherDatabase") .fallbackToDestructiveMigration() .build() } @Provides @Singleton fun provideWeatherDao(weatherDatabase: WeatherDatabase): WeatherDao { return weatherDatabase.weatherDao() } @Provides @Singleton fun provideWeatherRepository(weatherDao: WeatherDao): WeatherRepository { return WeatherRepository(weatherDao) } }
额外确认项
- 你的
WeatherApplication已添加@HiltAndroidApp注解,配置正确 MainActivity已添加@AndroidEntryPoint注解,符合Hilt注入要求- Hilt版本2.47无兼容性问题,保持依赖版本一致即可
内容的提问来源于stack exchange,提问作者Yauheni Mokich
相关产品推荐
相关产品推荐

