Anarchofascist
Anarchofascist

Reputation: 474

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 } 

Upvotes: 0

Views: 1216

Answers (2)

Henrik Schinzel
Henrik Schinzel

Reputation: 23

The accepted answer did not work for me in Kodein 5 (5.3.0). The below did.

class Die(val sides: Int)

fun main(args: Array<String>) {
  val kodein = Kodein {
    bind<Die>() with factory { sides: Int -> Die(sides) }
  }
  val die: Die by kodein.instance { 20 }
  println("Sides ${die.sides}")
}

Upvotes: 0

Salomon BRYS
Salomon BRYS

Reputation: 9584

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).

Upvotes: 2

Related Questions