For some reason Dagger doesn't generate DaggerApplicationComponent for my component. I tried: rebuilding, cleaning, invalidating cache, restarting Android Studio and etc. Nothing worked for me. Here is the full code:
Modules
@Module
class AppModule {
@Provides
@Singleton
fun provideContext(): Context = provideContext()
}
@Module
class DatabaseModule {
@Provides
@Singleton
open fun provideRoom(context: Context): RoomDatabase =
Room.databaseBuilder(
context,
AppDatabase::class.java,
DATABASE_NAME
).build()
}
@Module
class NetworkModule {
private val json = Json { ignoreUnknownKeys = true }
private val client = OkHttpClient.Builder()
.addInterceptor(TokenInterceptor)
.build()
@Provides
@Singleton
open fun provideRetrofit(): Retrofit =
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
.client(client)
.build()
}
Component
@Singleton
@Component(modules = [AppModule::class, DatabaseModule::class, NetworkModule::class])
interface ApplicationComponent {
fun inject(defaultRepository: DefaultRepository)
fun inject(myApplication: MyApplication)
}
Also in build.gradle file i use
implementation 'com.google.dagger:dagger-android:2.35.1'
implementation 'com.google.dagger:dagger-android-support:2.35.1' // if you use the support libraries
kapt 'com.google.dagger:dagger-android-processor:2.35.1'
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlinx-serialization'
id 'kotlin-kapt'
}
Application
class MyApplication : Application() {
val myApplication = DaggerApplicationComponent.builder().build()
}
Since you are using Dagger Android, it seems that the way you inject the app module into the application is wrong.
Please correct it as follows:
In the app component, you should extend from AndroidInjector
, specifically as follows:
app_component.kt
@Singleton
@Component(modules = [AppModule::class, DatabaseModule::class, NetworkModule::class])
interface ApplicationComponent : AndroidInjector<MyApplication> {
@Component.Factory
abstract class Factory : AndroidInjector.Factory<MyApplication>
}
Next is MyApplication
. When you use dagger android, you should extend from DaggerApplication()
. Just like that:
my_application.kt
class MyApplication : DaggerApplication() {
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
return DaggerAppComponent.factory().create(this)
}
}
And finally, you should clean and rebuild your project.
And one more thing, make sure you add all the Dagger android libraries.
app build.gradle.kts
plugins {
id("kotlin-kapt")
}
dependencies {
implementation("com.google.dagger:dagger:2.37")
implementation("com.google.dagger:dagger-android:2.37")
implementation("com.google.dagger:dagger-android-support:2.37")
kapt("com.google.dagger:dagger-android-processor:2.37")
kapt("com.google.dagger:dagger-compiler:2.37")
}