我想用Dagger Hilt设置两个Retrofit 2客户端,因为我的应用程序从两个不同的API获取信息。但是当我运行代码时,抛出了以下异常-〉
App_HiltComponents.java:128: error: [Dagger/DuplicateBindings] retrofit2.Retrofit is bound multiple times:
public abstract static class SingletonC implements HiltWrapper_ActivityRetainedComponentManager_ActivityRetainedComponentBuilderEntryPoint,
^
@org.jetbrains.annotations.NotNull @Provides retrofit2.Retrofit de.kotlinbooks.di.NetworkBooksModule.retrofitBooks(okhttp3.OkHttpClient)
@org.jetbrains.annotations.NotNull @Provides retrofit2.Retrofit de.kotlinbooks.di.NetworkNYTModule.retrofitNYT(okhttp3.OkHttpClient)
我知道翻新客户端是一个单例,所以我将模块分为两个文件,用于不同的API。
网络图书模块
@Module
@InstallIn(SingletonComponent::class)
class NetworkBooksModule {
@Provides
fun okHttpClient(): OkHttpClient {
val levelType: HttpLoggingInterceptor.Level = if (BuildConfig.DEBUG)
HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
val logging = HttpLoggingInterceptor()
logging.setLevel(levelType)
return OkHttpClient.Builder()
.addInterceptor(logging)
.build()
}
@Provides
fun retrofitBooks(okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl("https://www.googleapis.com/books/v1/")
.client(okHttpClient)
.addConverterFactory(MoshiConverterFactory.create())
.build()
}
@Provides
fun bookService(retrofit: Retrofit): BookService {
return retrofit.create(BookService::class.java)
}
@Provides
fun bookClient(bookService: BookService): BookClient {
return BookClient(bookService)
}
}
网络NYT模块
@Module
@InstallIn(SingletonComponent::class)
class NetworkNYTModule {
@Provides
fun okHttpClient(): OkHttpClient {
val levelType: HttpLoggingInterceptor.Level = if (BuildConfig.DEBUG)
HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
val logging = HttpLoggingInterceptor()
logging.setLevel(levelType)
return OkHttpClient.Builder()
.addInterceptor(logging)
.build()
}
@Provides
fun retrofitNYT(okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl("https://api.nytimes.com/svc/books/v3/")
.client(okHttpClient)
.addConverterFactory(MoshiConverterFactory.create())
.build()
}
@Provides
fun nytService(retrofit: Retrofit): NYTService {
return retrofit.create(NYTService::class.java)
}
@Provides
fun nytClient(nytService: NYTService): NYTClient {
return NYTClient(nytService)
}
}
2条答案
按热度按时间3ks5zfa01#
您可以使用界面来提供改造,而不是改造本身
bf1o4zei2#