【问题标题】:API interface dependency injection with hilt带 hilt 的 API 接口依赖注入
【发布时间】:2021-11-08 14:58:52
【问题描述】:

我是匕首的新手。

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

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 尖叫。

EDIT2:

这个配置也不行。

@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

【问题讨论】:

    标签: android kotlin


    【解决方案1】:

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

    【讨论】:

    • 具体实现是什么意思?具体方法?
    • stackoverflow.com/questions/3100410/…。非抽象实现 - 可以实例化的实际实现。当您在系统中注入类型时,需要在某个地方提供实现。提供的实现必须是具体的——它必须定义所有这些抽象函数。
    • 非常感谢,我已经很好地理解了这一点。我不能@Provides 任何接口,但我可以使用抽象类或普通类来提供,但我认为这不是我的情况。取而代之的是,我仍然想使用界面,但是我不确定如何使它不让 Dagger 对我尖叫。我想请您写下您的建议,并请在主帖中查看我上面的编辑。我不需要像带有方法{}的类这样的直接方法实现,我想在这里使用接口。
    • 我检查了这个例子,但还是不行。 stackoverflow.com/questions/63625370/…
    • 这很有趣,我只是在尝试stackoverflow.com/questions/46618763/…
    猜你喜欢
    • 2021-05-31
    • 2018-09-02
    • 2017-06-10
    • 1970-01-01
    • 2023-03-23
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多