kotlin 错误[Dagger/DependencyCycle]找到依赖关系循环

zdwk9cvp  于 2023-03-19  发布在  Kotlin
关注(0)|答案(1)|浏览(192)

我正在使用hilt并且我尝试修复这个错误。但是我无法修复这个错误。我想使用拦截器来刷新我的令牌(当不推荐使用时)。我共享了我的网络模块类和拦截器类。当使用依赖注入库时,我如何在拦截器类中请求API服务方法
拦截器类别:

class AuthInterceptor @Inject constructor(private val apiService: ApiService) : Interceptor, Authenticator {

    private val preferenceProvider = PreferenceProvider()

    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        request = request.newBuilder()
            .addHeader("Content-Type", "application/json")
            .addHeader("Accept", "application/json")
            .build()
        return chain.proceed(request)
    }

    override fun authenticate(route: Route?, response: Response): Request? {
        val token = preferenceProvider.getString(PREF_TOKEN) ?: return null
        ....        
        return null
    }
}

网络模块类:

@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {

    @Singleton
    @Provides
    fun provideHttpClient(authInterceptor: AuthInterceptor): OkHttpClient {
        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.HEADERS
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        val builder = OkHttpClient.Builder()
        builder.addInterceptor(interceptor)
            .connectTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .addInterceptor(authInterceptor)
            .authenticator(authInterceptor)
        return builder.build()
    }

    @Singleton
    @Provides
    fun provideConverterFactory(): GsonConverterFactory {
        return GsonConverterFactory.create()
    }

    @Singleton
    @Provides
    fun provideRetrofitInstance(okHttpClient: OkHttpClient, gsonConverterFactory: GsonConverterFactory) : Retrofit {
        return Retrofit.Builder().baseUrl(BASE URL).client(okHttpClient).addConverterFactory(gsonConverterFactory).build()
    }

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

我的错误:
.ApiService在身份验证拦截器(apiService)处注入。身份验证拦截器在.网络模块处注入。provideHttpClient(身份验证拦截器)okhttp3. OkHttpClient在.网络模块处注入。provideRetrofitInstance(okHttpClient,·)retrofit2. Retrofit在.网络模块处注入。provideApiService(retrofit).ApiService在.身份验证拦截器(apiService)处注入...

sxissh06

sxissh061#

这是一个循环依赖性问题。此身份验证器是改型服务中使用的Okhttp的一部分。
解决这个问题的方法是使用一个单独的retrofit示例,该示例使用一个没有身份验证器的okhttp。
可以使用命名改造示例

相关问题