Kodein constructor injecting Kodein$NotFoundException

798 views Asked by At

For some reason I can't get constructor injection to work with Kodein.

This is the code to reproduce the exception:

import org.kodein.di.Kodein
import org.kodein.di.direct
import org.kodein.di.generic.bind
import org.kodein.di.generic.instance
import org.kodein.di.generic.provider

fun main(args: Array<String>) {
    val kodein = Kodein {
        bind<Test2>() to provider { Test2() }
        bind<Test>() to provider { Test(instance()) }
    }

    val test = kodein.direct.instance<Test>()
}

class Test(val test2: Test2)
class Test2

The exception:

Exception in thread "main" org.kodein.di.Kodein$NotFoundException: No binding found for bind<Test>() with ? { ? }
Registered in this Kodein container:

    at org.kodein.di.internal.KodeinContainerImpl.factory(KodeinContainerImpl.kt:174)
    at org.kodein.di.KodeinContainer$DefaultImpls.factory$default(KodeinContainer.kt:33)
    at org.kodein.di.KodeinContainer$DefaultImpls.provider(KodeinContainer.kt:80)
    at org.kodein.di.internal.KodeinContainerImpl.provider(KodeinContainerImpl.kt:7)
    at org.kodein.di.KodeinContainer$DefaultImpls.provider$default(KodeinContainer.kt:79)
    at org.kodein.di.internal.DKodeinBaseImpl.Instance(DKodeinImpl.kt:33)
    at AppKt.main(App.kt:20)

Why doesn't this work?

1

There are 1 answers

0
Salomon BRYS On BEST ANSWER
bind<Test2>() to provider { Test2() }
              ^^

This is Kotlin's to function, that generates a Pair, nothing to do with Kodein's DSL :p

Kodein's DSL uses with:

bind<Test2>() with provider { Test2() }
              ^^^^

Note that, when you are binding a type to itself, you can use a simpler syntax:

bind() from provider { Test2() }