在我的应用程序中,我使用 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,我在MyApplication
andMyApplicationTest
类中实现了函数
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 类存在问题