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

如何构建Hilt模块,为Repository提供Api与Room并注入ViewModel

Hilt模块结构规划与Repository注入解决方案

模块拆分最优策略

不需要将所有逻辑塞进一个模块,也不用为每个类单独创建模块,按功能/组件类型分组拆分是最合理的方案:

  • 网络API相关逻辑放在独立的NetworkModule
  • Room数据库相关逻辑放在DatabaseModule
  • Repository可单独放在RepositoryModule(或与数据层强相关的模块结合,单独拆分更清晰)

这种拆分方式能让代码边界清晰,维护时不会影响无关模块,也符合Hilt的依赖注入设计思路。

修复当前错误并实现正确依赖注入

你的Repository需要同时依赖Room的DAO和API服务,只需在Repository的提供者方法中注入这两个依赖即可。以下是完整修改后的代码示例:

网络API模块(规范命名)

@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {

    @Provides
    @Named("mkBaseUrl")
    fun provideBaseUrl() = "https://..."

    @Provides
    @Singleton
    @Named("mkRetrofit")
    fun provideMkRetrofit(@Named("mkBaseUrl") baseUrl: String): Retrofit {
        // 补全Retrofit构建逻辑(示例)
        return Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .client(OkHttpClient.Builder().build())
            .build()
    }

    @Provides
    @Singleton
    fun provideMKApiService(@Named("mkRetrofit") retrofit: Retrofit): IMKApiService =
        retrofit.create(IMKApiService::class.java)
}

Room数据库模块

@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
    @Provides
    @Singleton
    fun provideDatabase(@ApplicationContext appContext: Context): AppDatabase =
        Room.databaseBuilder(
            appContext,
            AppDatabase::class.java,
            "room_database"
        ).build()

    @Provides
    @Singleton
    fun provideAgendamentosDao(database: AppDatabase): AgendamentosDao =
        database.agendamentosDao()
}

Repository模块

@Module
@InstallIn(SingletonComponent::class)
object RepositoryModule {

    @Provides
    @Singleton
    fun provideAgendamentosRepository(
        dao: AgendamentosDao,
        apiService: IMKApiService
    ): AgendamentosRepository =
        AgendamentosRepository(dao, apiService)
}

ViewModel注入

使用@HiltViewModel注解,通过构造函数直接注入Repository:

@HiltViewModel
class AgendamentosViewModel @Inject constructor(
    private val repository: AgendamentosRepository
) : ViewModel() {
    // 业务逻辑:调用Repository的方法获取/缓存数据
}

关键说明

  1. 依赖自动关联:Hilt会自动识别跨模块的依赖,只要所有模块都安装在SingletonComponent中,就能找到DAO和API服务的提供者,无需手动处理依赖传递。
  2. 单例作用域:Repository依赖的DAO和API服务都是单例,因此Repository也标记为@Singleton,保证全局唯一实例,避免重复初始化资源。
  3. 简化命名注解:如果你的项目中只有一个IMKApiService实现,可以去掉@Named("mkApiService"),进一步简化代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 01:01:08