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

如何向Hilt Worker注入非SingletonComponent的依赖?

问题:Hilt Worker注入ViewModel作用域仓库的处理方案

当使用@HiltWorker注解的Worker尝试注入仓库类时,Hilt明确规定仅SingletonComponent中可用的依赖可注入至Worker。但如果仓库类的作用域被限定为@ViewModelComponent(例如示例中IFirestoreRepository绑定在ViewModelComponent且标注@ViewModelScoped),该如何突破这个限制?毕竟仅允许注入单例依赖的约束比较严苛,很多业务场景下仓库类都会被设置为ViewModel作用域。

示例代码

Worker类代码

@HiltWorker
class WorkerGetData @AssistedInject constructor(
    @Assisted val context: Context,
    @Assisted workerParameters: WorkerParameters,
    val firestore: IFirestoreRepository,
    ): CoroutineWorker(context, workerParameters) { ... }

仓库绑定Module代码

@Module
@InstallIn(ViewModelComponent::class)
abstract class BindFirestore {
    @Binds
    @ViewModelScoped
    abstract fun bindFirestoreRepository(firestoreRepository: FirestoreRepository): IFirestoreRepository
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 12:10:29