Dagger2生成多个改装拦截器实例

时间:2018-08-31 06:59:47

标签: android kotlin retrofit dagger

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

这是我的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
}
}

1 个答案:

答案 0 :(得分:1)

如果进行构造函数注入,则无需制作Provide方法。

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

@Provides
@Singleton
fun provideHttpClient(interceptor: HttpLoggingInterceptor,
        headerInterceptor: AuthorizationInterceptor): OkHttpClient {

    return OkHttpClient.Builder()
        .addInterceptor(interceptor)
        .addInterceptor(headerInterceptor)
        .build()
}

或者,如果您不喜欢上面的解决方案,则可以在@Singleton类中删除@InjectAuthorizationInterceptor