Search code examples
kotlinkodein

Kodein factory bindings is throwing NotFoundException


I don't know if this is a bug or I'm just doing it wrong. I see nothing in the documentation that says that kodein factory bindings should be called in any way other than this:

class KodeinConfidenceTest {
    @Test
    fun testThatKodeinWorks() {
        val kodein = Kodein {
            bind<Dice>() with factory { sides: Int -> RandomDice(sides) }
        }
        val d:Dice = kodein.instance(5)
    }
}
open class Dice
data class RandomDice(val sides:Int) : Dice()

...but this causes a NotFoundException

com.github.salomonbrys.kodein.Kodein$NotFoundException: No provider found for bind<Dice>("5") with ? { ? }
Registered in Kodein:
    bind<Dice>() with factory { Int -> RandomDice } 

Solution

  • You should never write kodein.instance(5), you should write kodein.instance(tag = 5)

    Now you see your error. You are setting the tag (which differentiates bindings), not the argument to the factory.

    In Kodein 4, the syntax is either kodein.with(5).instance() or kodein.factory<Int, Dice>().invoke(5)

    I am currently developping Kodein 5 (no release schdule yet), in which this syntax will be changed to kodein.instance(arg = 5).