为什么在ViewModelProvider.Factory实现中添加@Singleton批注会导致编译错误[Dagger/MissingBinding]? [英] Why adding @Singleton annotation to ViewModelProvider.Factory implementation causes a compile error [Dagger/MissingBinding]?
问题描述
在此示例中,我一直尝试使用Dagger2注入ViewModelProvider.Factory
实现:
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:
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.
我花了两天的时间来寻找解决方案,所有内容都与通配符有关,并使用了我在课堂上已经使用过的@JvmSuppressWildcards
批注,我还尝试在构造函数签名中将Map
更改为MutableMap
只是得到了同样令人沮丧的错误,直到我不小心从以下位置删除了@Singleton
:
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:
@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)
}
}
}
然后,我的proyect编译了,那个烦人的错误消失了!我在做什么错了?
and after that, my proyect compiled and that annoying error disappeared! what am I doing wrong?
推荐答案
正如 David Medenjak 正确指出的那样,问题与范围有关,事实证明我在我的MainActivityModule
中包括了ViewModelModule
,而不是在我的AppModule
中,并且由于组件/子组件结构AppModule
不知道如何提供@Provides
位于子子组件内.
As David Medenjak correctly pointed out, the problem was related to the scopes, it turned out that I was including ViewModelModule
in my MainActivityModule
and not in my AppModule
and due to component/subcomponent structure AppModule
didn't know how to provide the GithubViewModelFactory
because the @Provides
was inside a child subcomponent.
这篇关于为什么在ViewModelProvider.Factory实现中添加@Singleton批注会导致编译错误[Dagger/MissingBinding]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!