代码之家  ›  专栏  ›  技术社区  ›  Jan Wytze

Kodein构造函数注入Kodein$NotFoundException

  •  0
  • Jan Wytze  · 技术社区  · 6 年前

    这是重现异常的代码:

    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
    

    例外情况:

    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)
    

    1 回复  |  直到 6 年前
        1
  •  0
  •   Salomon BRYS    6 年前
    bind<Test2>() to provider { Test2() }
                  ^^
    

    这是科特林的 to 函数,生成 Pair ,与Kodein的DSL无关:p

    Kodein的DSL使用 with :

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

    请注意,将类型绑定到自身时,可以使用更简单的语法:

    bind() from provider { Test2() }