You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中Kodein依赖注入引发强制关闭错误的求助

解决Kodein依赖注入中找不到ViewModelFactory绑定的崩溃问题

你的崩溃原因其实在错误信息里已经给出了关键线索——类名的单复数拼写不匹配!仔细看错误日志:

Caused by: org.kodein.di.Kodein$NotFoundException: No binding found for bind() with ? { ? }
Registered in this Kodein container:
...
bind() with provider { QuotesViewModelFactory }
...

你在Activity中尝试注入的是QuoteViewModelFactory(单数Quote),但在Application的Kodein配置里注册的是QuotesViewModelFactory(复数Quotes)。Kodein是严格基于类型匹配查找依赖的,哪怕只是类名差一个字母,都会导致找不到绑定。

解决方案步骤:

  1. 统一类名拼写
    先确认你的ViewModelFactory类的实际类名:

    • 如果类确实叫QuotesViewModelFactory(带s),把Activity中的类型声明改成一致:
      private val viewModelFactory: QuotesViewModelFactory by instance()
      
    • 如果类是QuoteViewModelFactory(不带s),修正Application里的绑定代码:
      bind() from provider { QuoteViewModelFactory(instance()) }
      
  2. 额外验证确保配置正确

    • 确认QuoteDiApp已经在AndroidManifest.xml中正确注册,示例配置如下:
      <application
          android:name=".QuoteDiApp"
          android:allowBackup="true"
          android:icon="@mipmap/ic_launcher"
          android:label="@string/app_name"
          android:roundIcon="@mipmap/ic_launcher_round"
          android:supportsRtl="true"
          android:theme="@style/Theme.YourAppName">
          <!-- 你的Activity声明 -->
      </application>
      
    • 检查QuoteViewModelFactory的构造函数是否依赖QuoteRepository,你的代码中QuoteRepository的绑定是正常的,这部分无需调整。

小提示

这类拼写差异问题很容易在复制代码或重构类名时出现,下次遇到Kodein的NotFoundException,优先对比错误信息里“找不到的类型”和“已注册的类型”,通常能快速定位问题。

内容的提问来源于stack exchange,提问作者Jake warton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:49:06