'Android dagger: How to provide subclassed Application object to build dependency and avoid cast to Application

I have a subclass of the Application class and I need to invoke a method from that subclass in the Dagger Module class to provide a dependency. Is it possible to "provide" MyApplication object at all? I am trying to avoid casting to ApplicationContext to MyApplication here

@Singleton
@Provides
OkHttpClient okHttpClient(@ApplicationContext Context applicationContext,
        HttpLoggingInterceptor httpLoggingInterceptor,
        NetworkEndpointInterceptor networkEndpointInterceptor) {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();

    builder.addInterceptor(networkEndpointInterceptor);
    if (applicationContext instanceof MyApplication) {
        List<Interceptor> interceptors = ((MyApplication) applicationContext).getInterceptors();
        for (Interceptor interceptor: interceptors) {
            builder.addInterceptor(interceptor);
        }
    }
    builder.addNetworkInterceptor(httpLoggingInterceptor);

    return builder
            .build();
}

MyApplication.kt:

@HiltAndroidApp
open class MyApplication : Application() {
    ...
    open val interceptors = mutableListOf<Interceptor>()
    ...
}


Solution 1:[1]

You can provide all your dependencies inside di graph and avoid to use the custom app implementation.

But, if you still need this, you can try to create dagger module, bind application variable to your MyApplication and install this module in SingletonComponent. Somthing like that:

@Module
@InstallIn(SingletonComponent::class)
class AppModule {

    @Provides
    fun provideMyApp(impl: Application): MyApplication {
        return impl as MyApplication
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sotin Semyon