Search code examples
androidkotlindaggerkodein

I'm struggling to understand Dagger. Can someone me how this Kodein implementation would look in Dagger?


I am required to learn Dagger 2 for a new project and am struggling a bit to make sense of it all.

I've looked at some Tutorials which give some clarity but I'm still confused by quite a bit, for example how the various moving pieces (Components, Modules, Injectors, Providers) all relate to each other.

Im thinking that perhaps if someone could show me A Dagger equivalent implementation of the code below using Kodein for dependency injection, that would help bridging my gap in understanding:

Injection.kt

fun depInject(app: Application): Kodein {
    return lazy {
        bind<Application>() with instance(app)
        bind<Context>() with instance(app.applicationContext)
        bind<AnotherClass>() with instance(AnotherClass())   
    }
}

BaseApplication.kt

class BaseApplication: Application() {

    companion object {
        lateinit var kodein: Kodein
            private set
    }

    override fun onCreate() {
        super.onCreate()
        kodein = depInject(this)
    }
}

and then anywhere I need to inject I just use:

 private val context: Context by BaseApplication.kodein.instance()

Thanks!


Solution

  • fun depInject(app: Application): AppComponent {
        return lazy {
            DaggerAppComponent.factory().create(app)
        }
    }
    

    and

    @Singleton
    @Component(modules = [AppModule::class])
    interface AppComponent {
        fun context(): Context
    
        @Component.Factory
        interface Factory {
            fun create(@BindsInstance app: Application): AppComponent
        }
    }
    
    @Module
    object AppModule {
        @Provides 
        @JvmStatic
        fun context(app: Application): Context = app.applicationContext
    }
    

    Then

    class BaseApplication: Application() {
    
        companion object {
            lateinit var component: AppComponent
                private set
        }
    
        override fun onCreate() {
            super.onCreate()
            component = depInject(this)
        }
    }
    

    And

    private val context: Context by lazy { BaseApplication.component.context() }
    

    EDIT:

    @Singleton class AnotherClass @Inject constructor() {
    }
    
    @Singleton
    @Component(/*...*/)
    interface AppComponent {
        ...
    
        fun anotherClass(): AnotherClass
    
        ...
    }