[英]Why adding @Singleton annotation to ViewModelProvider.Factory implementation causes a compile error [Dagger/MissingBinding]?
I've been trying to use Dagger2 to inject a ViewModelProvider.Factory
implementation as in this example: GithubBrowserExample I copied the exact same class, however, when I try to build I get the following error: 我一直在尝试使用Dagger2注入一个
ViewModelProvider.Factory
实现,例如以下示例: GithubBrowserExample我复制了完全相同的类,但是,当我尝试构建时,出现以下错误:
error: [Dagger/MissingBinding] [dagger.android.AndroidInjector.inject(T)] java.util.Map<java.lang.Class<? extends android.arch.lifecycle.ViewModel>,javax.inject.Provider<android.arch.lifecycle.ViewModel>> cannot be provided without an @Provides-annotated method.
I've spent 2 days trying to find a solution and everything was about wildcards and using @JvmSuppressWildcards
annotation which I had already used in my class, I also tried to change Map
for MutableMap
in the constructor signature only to get the same frustrating error, until I accidentally removed @Singleton
from: 我花了两天的时间来寻找解决方案,所有内容都与通配符有关,并使用了我在课堂上已经使用过的
@JvmSuppressWildcards
批注,我还尝试更改构造函数签名中的Map
for MutableMap
,以得到同样令人沮丧的错误,直到我不小心从以下位置删除了@Singleton
:
@Singleton
class GithubViewModelFactory @Inject constructor(
private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val creator = creators[modelClass] ?: creators.entries.firstOrNull {
modelClass.isAssignableFrom(it.key)
}?.value ?: throw IllegalArgumentException("unknown model class $modelClass")
try {
@Suppress("UNCHECKED_CAST")
return creator.get() as T
} catch (e: Exception) {
throw RuntimeException(e)
}
}
}
and after that, my proyect compiled and that annoying error disappeared! 之后,我的proyect编译了,那个烦人的错误消失了! what am I doing wrong?
我究竟做错了什么?
正如David Medenjak正确指出的那样,问题与范围有关,事实证明我将ViewModelModule
包含在MainActivityModule
,而不包含在AppModule
并且由于组件/子组件结构, AppModule
不知道如何提供GithubViewModelFactory
因为@Provides
位于子子组件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.