【问题标题】:Dagger2 generating multiple instances of retrofit interceptorDagger2 生成改造拦截器的多个实例
【发布时间】:2018-08-31 06:59:46
【问题描述】:

Dagger 2 正在生成多个改装拦截器实例,尽管在 dagger 模块中将其标记为单例。现在的问题是 AuthorizationInterceptor 构造函数被调用了两次,我不明白为什么,因为我在从登录 API 获取结果后设置的标头设置为不同的 Interceptor 实例,同时调用其他一些需要的 API authenticationToken 令牌未设置。

这是我的 ApiModule

@Module
open class ApiModule {

@Provides
@Singleton
fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor {
    val loggingInterceptor = HttpLoggingInterceptor()
    loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
    return loggingInterceptor
}

@Provides
@Singleton
fun provideHeaderInterceptor(): Interceptor {
    return AuthorizationInterceptor()
}

@Provides
@Singleton
fun provideHttpClient(interceptor: HttpLoggingInterceptor, headerInterceptor: Interceptor): OkHttpClient {
    return OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .addInterceptor(headerInterceptor)
            .build()
}

@Provides
@Singleton
fun provideMoshi(): Moshi {
    return Moshi.Builder()
            .build()
}

@Provides
@Singleton
fun provideRetrofit(client: OkHttpClient, moshi: Moshi, apiConfig: ApiConfig): Retrofit {
    return Retrofit.Builder()
            .baseUrl(apiConfig.baseUrl)
            .client(client)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .build()
}

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

这是我的 AuthorizationInterceptor 类

@Singleton
class AuthorizationInterceptor @Inject constructor() : Interceptor {

override fun intercept(chain: Interceptor.Chain?): Response {
    val request = chain?.request()
    val requestBuilder = request?.newBuilder()
    if (request?.header("No-Authorization") == null && authorization.isNotEmpty()) {
        requestBuilder?.addHeader("Authorization", authorization)
    }
    return chain?.proceed(requestBuilder!!.build())!!
}

private var authorization: String = ""
fun setSessionToken(sessionToken: String) {
    this.authorization = sessionToken
}
}

【问题讨论】:

    标签: android kotlin retrofit dagger


    【解决方案1】:

    如果进行构造函数注入,则不需要提供提供方法。

    删除provideHeaderInterceptor 方法,然后更新provideHttpClient 方法,如下所示,

    @Provides
    @Singleton
    fun provideHttpClient(interceptor: HttpLoggingInterceptor,
            headerInterceptor: AuthorizationInterceptor): OkHttpClient {
    
        return OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .addInterceptor(headerInterceptor)
            .build()
    }
    

    或者,如果您不喜欢上述解决方案,您可以删除 AuthorizationInterceptor 类中的 @Singleton@Inject

    【讨论】:

    • 谢谢他的工作,从昨天开始我一直在努力解决这个问题
    • NP,匕首需要时间消化。最好的问候,
    猜你喜欢
    • 2017-12-18
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 2016-11-15
    • 2020-08-11
    • 1970-01-01
    相关资源
    最近更新 更多