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

使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 02:45:13