Search code examples
androiddagger-2dagger

How to work with DaggerApplication and DaggerAppCompatActivity


I'm trying to get my head around the new Dagger2 APIs and support for Android. I'm using Dagger2 version 2.15:

implementation 'com.google.dagger:dagger:2.15'
implementation 'com.google.dagger:dagger-android:2.15'
implementation 'com.google.dagger:dagger-android-support:2.15'
annotationProcessor 'com.google.dagger:dagger-compiler:2.15'
annotationProcessor 'com.google.dagger:dagger-android-processor:2.15'

Now in this version there are some classes like DaggerApplication and DaggerAppCompatActivity but I'm not sure how to get them to work.

This is what I've done so far:

My Application class which I added in the manifest:

class BaseApplication : DaggerApplication() {
    override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
        return DaggerAppComponent.builder().create(this)
    }
}

My AppComponent:

@Singleton
@Component(modules = [
    AndroidSupportInjectionModule::class
])
interface AppComponent : AndroidInjector<BaseApplication> {
    @Component.Builder
    abstract class Builder : AndroidInjector.Builder<BaseApplication>()
}

And my base Activity class that I extend in any other activity that I create:

abstract class BaseActivity : DaggerAppCompatActivity() {
}

The problem is that when I try to make or build the project it fails and Dagger doesn't generate DaggerAppComponent for me. What do I miss?


Solution

  • Need more info but try this AppComponent

    @Singleton
    @Component(modules = [AndroidSupportInjectionModule::class])
    interface ApplicationComponent : AndroidInjector<YourApplication> {
        override fun inject(application: YourApplication)
    
        @Component.Builder
        interface Builder {
            @BindsInstance
            fun application(application: YourApplication): Builder
    
            fun build(): ApplicationComponent
        }
    }
    

    And from your application class

    class YourApplication : DaggerApplication() {
        private val applicationInjector = DaggerApplicationComponent.builder()
            .application(this)
            .build()
    
        override fun applicationInjector() = applicationInjector
    }
    

    Also use kapt instead of annotationProcessor from your build.gradle :

    apply plugin: 'kotlin-kapt'
    ...
    kapt 'com.google.dagger:dagger-compiler:2.15'
    kapt 'com.google.dagger:dagger-android-processor:2.15'