【问题标题】:Dagger Hilt: cannot be provided without an @Provides-annotated methodDagger Hilt:没有@Provides-annotated 方法就不能提供
【发布时间】:2021-01-30 08:38:09
【问题描述】:

当我在视图模型中使用如下界面时

class MainViewModel @ViewModelInject constructor(
    private val trafficImagesRepository: TrafficImageRepository, <----------------- Not working
    @Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel() 

我收到如下错误

cannot be provided without an @Provides-annotated method.
  public abstract static class SingletonC implements MainApplication_GeneratedInjector,

我的界面如下图

interface TrafficImageRepository {
    suspend fun getTrafficImages() : NetworkResponse<TrafficData, ErrorTrafficImages>
}

Repository 类如下所示

class DefaultTrafficImagesRepository @Inject constructor(private val trafficImageService: TrafficImageService) : TrafficImageRepository {

    override suspend fun getTrafficImages(): NetworkResponse<TrafficData, ErrorTrafficImages> {
        lateinit var response: NetworkResponse<TrafficData, ErrorTrafficImages>
        withContext(IO) {
            val currentTimestamp = Constants.getCurrentTime()
            response = trafficImageService.getTrafficImages(currentTimestamp)
        }
        return response
    }
}

但是当我直接使用 DefaultTrafficImagesRepository 类而不是 Interface 时,我的应用程序能够构建而没有任何错误。

class MainViewModel @ViewModelInject constructor(
    private val trafficImagesRepository: DefaultTrafficImagesRepository , <----------------- Working Fine
    @Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel()

【问题讨论】:

    标签: android dagger-hilt


    【解决方案1】:

    必须绑定接口

    @Module
    @InstallIn(ViewModelComponent::class)
    abstract class RepositoryModule {
    
        @Binds
        abstract fun bindRepository(impl: DefaultTrafficImagesRepository): TrafficImageRepository 
    }
    

    并以这种方式使用视图模型注入

    @HiltViewModel
    class MainViewModel @Inject constructor(
        private val trafficImagesRepository: TrafficImageRepository,
        @Assisted private val savedStateHandle: SavedStateHandle
    ) : ViewModel() 
    

    【讨论】:

    • 对于我使用了 FakeTrafficImageRepository 的测试用例,我是否也需要绑定它?
    • @PanchalAmit 您可以在测试中使用“UninstallModules”并通过您想要的新模块。
    • 成功了!我从ActivityComponent 更改为SingletonComponent,为什么它不适用于ActivityComponent
    • @DouglasFornaro 导致活动生命周期
    猜你喜欢
    • 2021-12-05
    • 2018-07-09
    • 1970-01-01
    • 2021-06-30
    • 2022-10-24
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多