问题
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.
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)
}
}
}
and after that, my proyect compiled and that annoying error disappeared! what am I doing wrong?
回答1:
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.
来源:https://stackoverflow.com/questions/52638747/why-adding-singleton-annotation-to-viewmodelprovider-factory-implementation-cau