我有2次注射同一類的,我用它們來創建2個改造API客戶端:命名注射不工作
改造實例:
@Provides
@Singleton
@Named(NO_REAUTH_RETROFIT)
fun provideNoAuthRetrofit(moshi: Moshi, okHttpClientBuilder: OkHttpClient.Builder): Retrofit {
return Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(Constants.apiUrlLive)
.client(okHttpClientBuilder.build())
.build()
}
@Provides
@Singleton
@Named(REAUTH_RETROFIT)
fun provideAuthRetrofit(moshi: Moshi, okHttpClientBuilder: OkHttpClient.Builder, interceptor: NetworkInterceptor): Retrofit {
return Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(Constants.apiUrlLive)
.client(okHttpClientBuilder.addInterceptor(interceptor).build())
.build()
}
OkHttp:
@Singleton
@Provides
fun provideOkHttpClientBuilder(context: Context, cache: Cache): OkHttpClient.Builder {
Stetho.initializeWithDefaults(context)
val httpLoggingInterceptor = HttpLoggingInterceptor()
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
val chuckInterceptor = ChuckInterceptor(context).showNotification(true)
return OkHttpClient.Builder()
.addInterceptor(chuckInterceptor)
.addInterceptor(httpLoggingInterceptor)
.addNetworkInterceptor(StethoInterceptor())
.cache(cache)
}
API實例:
@Provides
@Singleton
fun provideCartApi(@Named(REAUTH_RETROFIT) retrofit: Retrofit): CartApi {
return retrofit.create(CartApi::class.java)
}
@Provides
@Singleton
fun provideAuthApi(@Named(NO_REAUTH_RETROFIT) retrofit: Retrofit): AuthApi {
return retrofit.create(AuthApi::class.java)
}
這兩個API函數都接收NetworkInterceptor
的改進實例。我試圖切換2個改造實例的@Named
值,但沒有任何改變。只有當我從兩個翻新實例中刪除NetworkInterceptor
時,才創建API實例,但不包含NetworkInterceptor
。
我還檢查字節碼,但@Named
註釋存在有
你能告訴OkHttpClient.Builder'如何'是正在提供? – azizbekian
@azizbekian更新了這個問題。 – Sourabh