I am learning dagger hilt without learning dagger2 and came up with an error which I can't find a solution.

I have two methods provideLoggingInterceptor() and provideHeaderInterceptor() which returns the same Interceptor object so I added a @Named() qualifier to identify the providers. The provideOkHttpClient() methods needs both the Interceptor but I am getting a compile time error as

error: [Dagger/MissingBinding] okhttp3.Interceptor cannot be provided without an @Provides-annotated method.

Now I am confused because if both the methods provideLoggingInterceptor() and provideHeaderInterceptor() are annotated with the @Provides annotation then why am I getting error that one of my methods does not have @Provides annotation.

@InstallIn(ApplicationComponent::class)
@Module
class NetworkModule {

    val TIMEOUT = 10

    @Singleton
    @Provides
    @Named("logging")
    fun provideLoggingInterceptor(): Interceptor =
        HttpLoggingInterceptor().apply {
            level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY
            else HttpLoggingInterceptor.Level.NONE
        }

    @Singleton
    @Provides
    @Named("header")
    fun provideHeaderInterceptor(): Interceptor =
        Interceptor { chain ->
            val request = chain.request()
            val newUrl = request.url.newBuilder()
                .addQueryParameter("api_key", BuildConfig.TMBD_API_KEY)
                .build()
            val newRequest = request.newBuilder()
                .url(newUrl)
                .method(request.method, request.body)
                .build()
            chain.proceed(newRequest)
        }

    @Singleton
    @Provides
    fun provideOkHttpClient(
        logging: Interceptor,
        header: Interceptor
    ): OkHttpClient =
        OkHttpClient.Builder()
            .connectTimeout(TIMEOUT.toLong(), TimeUnit.SECONDS)
            .readTimeout(TIMEOUT.toLong(), TimeUnit.SECONDS)
            .addInterceptor(header)
            .addInterceptor(logging)
            .addNetworkInterceptor(StethoInterceptor())
            .build()
}
1

There are 1 answers

0
IR42 On BEST ANSWER

You must also use Named annotation for arguments

fun provideOkHttpClient(
        @Named("logging") logging: Interceptor,
        @Named("header") header: Interceptor
    ): OkHttpClient = ...