Alternative To Dagger Static Injection Using Component Getter

April 13, 2018
Dagger inject into global/singleton object

Dagger 2 does not support static injection.

The following code is based on sample in Setup Dagger 2 For Android Kotlin.

Setup the provider code for the object.

@Module(...)
internal class AppModule {
    ...
    @Singleton
    @Provides
    fun provideMoshi(): Moshi {
        return Moshi.Builder()
                .add(KotlinJsonAdapterFactory())
                .build()
    }
}

Create getter for object in Component class.

@Singleton
@Component(...)
interface AppComponent {
    ...

    fun getMoshi(): Moshi
}

You can retrieve the dagger component and access the object through the getter.

    val component = DaggerAppComponent.builder().build()
    val moshi = component.getMoshi()

You might want to store the compoment in singleton class for easy access.

object App {
  lateinit var daggerAppComponent: AppComponent
}
App.daggerAppComponent = DaggerAppComponent.builder().build()

...

val moshi = App.daggerAppComponent.getMoshi()
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.