首页 > 解决方案 > 带 hilt 的 API 接口依赖注入

问题描述

我是匕首的新手。

我创建了实现,在其中注入了构造函数,例如:

class ListItemsPagingSourceFactory @Inject constructor(
    private val api: Api,
    private val pageErrorsQueue: ListItemsPagingErrorsQueue
) {

}

interface Api {

    fun getList(
        count: Int,
        offset: Int
    ) : ListItemResponse

我的 api 接口有一个错误,我只想实现我的方法以供以后使用。但是会发生错误,例如:

Error: [Hilt]
public abstract interface Api {
                ^

当我添加@InstallIn @EntryPoint

到 API 接口:

error: [Hilt]
  @InstallIn, 'value' class is invalid or missing: @dagger.hilt.InstallIn({})
  [Hilt] Processing did not complete. See error above for details.

编辑:我有非常相似的实现,但是在我使用的地方进行改造(@Get,@Query 等)我想实现我自己的“API”,它只是从服务本地获取数据而不启动数据库的方法。这是来自 retrofitApi 的代码

interface RetrofitApi {
    @GET("data/mine")
    suspend fun getDataItems(
        @Query("count") count: Int,
        @Query("size") size: Int
    ): DataItemsResponse

如何将其更改为仅接口或抽象类,它只有方法而不启动 DB => 以在日志中没有 Dagger 尖叫。

编辑2:

此配置也不起作用。

@InstallIn
@Module(includes = [AppModule.Api::class])
class AppModule {
    // interface with @Binds
    @Module
    interface Api {
        @Binds
        fun getList(
            count: Int,
            offset: Int
        ) : ListItemResponse
    }
}

错误:

@Binds methods must have exactly one parameter, whose type is assignable to the return type

标签: androidkotlin

解决方案


由于 API 是一个抽象接口,因此您不会在其中添加这些注释。您可以将它们添加到具体的实现中。无论什么类都有那些 Dagger 需要能够实例化,它不能实例化一个抽象类。


推荐阅读