androiddagger-2android-glidedagger-hilt

Error using Hilt to inject OkHttpClient into AppGlideModule


I am trying to inject an OkHttpClient into an AppGlideModule using Hilt.

My network module provides the http client:

   @Singleton
   @Provides
   fun provideOkHttpClient(
      tokenInterceptor: Interceptor
   ): OkHttpClient {
      return OkHttpClient.Builder()
         .connectTimeout(60, TimeUnit.SECONDS)
         .readTimeout(60, TimeUnit.SECONDS)
         .writeTimeout(60, TimeUnit.SECONDS)
         .addInterceptor(tokenInterceptor)
         .build()
   }

Trying to inject into AppGlideModule:

@GlideModul
@Excludes(OkHttpLibraryGlideModule::class)
class MyGlideModule: AppGlideModule() {

    @Inject lateinit var httpClient: OkHttpClient

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory(httpClient))

    }
}

However when glide is initialed the http client is not injected as I am getting the following error:

Caused by: kotlin.UninitializedPropertyAccessException: lateinit property httpClient has not been initialized

I have also tried to use constructor injection with no luck


Solution

  • Hilt does not know how to provide dependencies to MyGlideModule because there is no entry point. You need to make one for the class.

    @EntryPoint
    @InstallIn(SingletonComponent::class)
    // entry point for MyGlideModule
    interface MyGlideEntryPoint {
        fun provideOkHttpClient(): OkHttpClient
    }
    

    In registerComponents, the application context will be provided as a parameter. Using the context, you can get the entry point to inject dependencies you need.

    @GlideModule
    @Excludes(OkHttpLibraryGlideModule::class)
    class MyGlideModule : AppGlideModule() {
        override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
            // get MyGlideEntryPoint from context
            val entryPoint = EntryPoints.get(context, MyGlideEntryPoint::class.java)
    
            // get HttpClient from the entry point
            val httpClient = entryPoint.provideOkHttpClient()
    
            registry.replace(
                GlideUrl::class.java,
                InputStream::class.java,
                OkHttpUrlLoader.Factory(httpClient)
            )
        }
    
        @EntryPoint
        @InstallIn(SingletonComponent::class)
        interface MyGlideEntryPoint {
            fun provideOkHttpClient(): OkHttpClient
        }
    }
    

    If you need more info about Hilt's entry point, see https://dagger.dev/hilt/entry-points