1

在我的应用程序中,我使用 Hilt 进行依赖注入。我在我的存储库中实现了一个RetrofitModule为它提供依赖项,如下所示:

@Module
@InstallIn(ApplicationComponent::class)
object RetrofitModule {

    @Singleton
    @Provides
    fun providesRetrofitClient(okHttpClient: OkHttpClient, baseUrl: String): Retrofit {
        return Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build()
    }

    @Provides
    fun providesBaseUrl(application: MyApplication): String {
        return application.getBaseUrl()
    }

    @Singleton
    @Provides
    fun providesOkHttpClient(): OkHttpClient {
        val okHttpClientBuilder = OkHttpClient.Builder()
        val loggingInterceptor = HttpLoggingInterceptor().apply {
            level = HttpLoggingInterceptor.Level.BODY
        }
        okHttpClientBuilder.addInterceptor(loggingInterceptor)
        return okHttpClientBuilder.build()
    }

    @Singleton
    @Provides
    fun providesService(retrofit: Retrofit): MyService {
        return retrofit.create(MyService::class.java)
    }
}

为了为被测的 Mockwebserver 配置提供测试基础 url,我在MyApplicationandMyApplicationTest类中实现了函数

MyApplication.class

class MyApplication : Application() {
    fun getBaseUrl() = "https://www.foo-production.com"
}

MyApplicationTest.class

class MyApplicationTest : Application() {
    fun getBaseUrl() = "http://127.0.0.1:8080"
}

但是当我构建应用程序时,我收到了这个错误:

 A binding with matching key exists in component: de.xxx.xxx.MyApplication_HiltComponents.ApplicationC
      ...

我认为问题在于这种方法

@Provides
fun providesBaseUrl(application: MyApplication): String {
    return application.getBaseUrl()
}

并且通过提供 MyApplication 类存在问题

4

1 回答 1

2

A) 可能解决您的情况

Hilt 无法提供您的确切MyApplication实例,它只能提供一个通用实例(Application参见Hilt Components)。Component default bindings

这应该可以解决问题:

@Provides
fun providesBaseUrl(application: Application): String {
    return (application as MyApplication).getBaseUrl()
}

话虽如此,有一种更优雅的方式来实现它。

B) 优雅的方式

  1. src/main/your/package/创建一个UrlModule.kt
@Module
@InstallIn(ApplicationComponent::class)
object UrlModule {

    @Provides
    fun providesBaseUrl(application: MyApplication): String {
        return "https://www.foo-production.com"
    }

}
  1. src/test/your/package/(或者src/androidTest/your/package/如果它用于 UI 测试)创建另一个UrlModule.kt
@Module
@InstallIn(ApplicationComponent::class)
object UrlModule {

    @Provides
    fun providesBaseUrl(application: MyApplication): String {
        return "http://127.0.0.1:8080"
    }

}
于 2020-08-07T15:50:08.090 回答