Alternative To Dagger Static Injection Using Component Getter

Apr 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()

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.