错误[Dagger / MissingBinding]如果没有@Provides注释的方法,则无法提供androidx.lifecycle.ViewModelProvider.Factory [英] Error [Dagger/MissingBinding] androidx.lifecycle.ViewModelProvider.Factory cannot be provided without an @Provides-annotated method

查看:955
本文介绍了错误[Dagger / MissingBinding]如果没有@Provides注释的方法,则无法提供androidx.lifecycle.ViewModelProvider.Factory的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用匕首2.2实现MultiBinding时遇到问题。我在MVVM体系结构中使用了匕首。我注入了 ViewModelProvideFactory 构造函数并绑定了模块的依赖关系。

I am facing an issue while implementing MultiBinding using dagger 2.2. I am using dagger with MVVM architecture. I have injected the ViewModelProvideFactory constructor and binds the dependency from module.

我遵循了YouTube上Mitch的教程

I have followed the tutorial of Mitch from youtube

https://www.youtube.com/watch?v=DToD1W9WdsE&list=PLgCYzUzKIBE8AOAspC3DHoBNZIBHbIOsC&index=13

我在这些链接上搜索了解决方案,但仍然面临相同的问题。

I have searched on these links for the solutions but still facing the same issue.

Dagger2:如果没有@Provides注释的方法,则无法提供ViewModel

Dagger / MissingBinding java.util.Map< java.lang.Class< ;?扩展ViewModel>,Provider< ViewModel>>没有@Provides批注的方法就无法提供

https://github.com/google/dagger/issues/1478

代码段

ViewModelKey

@MapKey
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ViewModelKey {
    Class<? extends ViewModel> value();
}

ViewModelFactoryModule

   /**
 * ViewModelFactoryModule responsible for providing [ViewModelProviderFactory]
 *
 * Annotated with Module to tell dagger it is a module to provide [ViewModelProviderFactory]
 *
 * Annotated with bind annotation to efficiently provide dependencies similar to provides annotation
 */
@Module
abstract class ViewModelFactoryModule {

    @Binds
    abstract fun bindViewModelFactory(viewModelFactory: ViewModelProviderFactory) : ViewModelProvider.Factory
}

ViewModelProviderFactory

@Singleton
class ViewModelProviderFactory @Inject
constructor(private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>) :
    ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
    var creator: Provider<out ViewModel>? = creators[modelClass]
    if (creator == null) { // if the viewmodel has not been created

        // loop through the allowable keys (aka allowed classes with the @ViewModelKey)
        for ((key, value) in creators) {

            // if it's allowed, set the Provider<ViewModel>
            if (modelClass.isAssignableFrom(key)) {
                creator = value
                break
            }
        }
    }

    // if this is not one of the allowed keys, throw exception
    if (creator == null) {
        throw IllegalArgumentException("unknown model class $modelClass")
    }

    // return the Provider
    try {
        return creator.get() as T
    } catch (e: Exception) {
        throw RuntimeException(e)
    }

}

    companion object {

        private val TAG = "ViewModelProviderFactor"
    }
}

StackTrace

> Task :app:kaptDebugKotlin FAILED
e: /Users/fazal/Documents/fazal/demo/AdvanceDagger2/app/build/tmp/kapt3/stubs/debug/com/example/advancedagger2/di/AppComponent.java:22: error: [Dagger/MissingBinding] java.util.Map<java.lang.Class<? extends androidx.lifecycle.ViewModel>,javax.inject.Provider<androidx.lifecycle.ViewModel>> cannot be provided without an @Provides-annotated method.
public abstract interface AppComponent extends dagger.android.AndroidInjector<com.example.advancedagger2.BaseApplication> {
                ^
      java.util.Map<java.lang.Class<? extends androidx.lifecycle.ViewModel>,javax.inject.Provider<androidx.lifecycle.ViewModel>> is injected at
          com.example.advancedagger2.viewmodel.ViewModelProviderFactory(viewModelsMap)
      com.example.advancedagger2.viewmodel.ViewModelProviderFactory is injected at
          com.example.advancedagger2.ui.AuthActivity.viewModelFactory
      com.example.advancedagger2.ui.AuthActivity is injected at
          dagger.android.AndroidInjector.inject(T) [com.example.advancedagger2.di.AppComponent → com.example.advancedagger2.di.ActivityBuilderModule_ContributeAuthActivity.AuthActivitySubcomponent]

我已经降级了Kotlin版本,但仍然面临相同的问题。告诉我,我做错了吗?

I have downgraded the Kotlin version but still facing the same issue. Tell me what, I am doing wrong?

编辑1

我还通过AuthViewModel提供ViewModel。活动范围。当活动破坏了它的组件并且依赖关系也被破坏了。

I am also providing ViewModel through AuthViewModel which is on the scope of activity. When activity destroys its component and dependencies also destroy.

AuthViewModelModule

@Module
abstract class AuthViewModelModule {

    /**
     * Binds the auth view model dependency with [ViewModelKey] to group similar [ViewModel]
     *
     * Under the hood it is providing [com.example.advancedagger2.viewmodel.AuthViewModel]
     */
    @Binds
    @IntoMap
    @ViewModelKey(AuthViewModel::class)
    abstract fun bindAuthViewModel(authViewModel: AuthViewModel) : ViewModel
}

ActivityBuilderModule

/**
 * This Class {@linkplain ActivityBuilderModule} is responsible for for android injection
 * for the activity with in the application to avoid the seprate injection in each activity
 *
 * {@linkplain dagger.android.AndroidInjection#inject(Activity)}
 *
 * {@link com.example.advancedagger2.viewmodel.AuthViewModel} can be access from Auth Activity
 * only so it is the concept of sub-modules
 *
 */
@Module
public abstract class ActivityBuilderModule {

    @ContributesAndroidInjector(
            modules = AuthViewModelModule.class
    )
    abstract AuthActivity contributeAuthActivity();
}


推荐答案

根据我的评论解决了这个问题

According to the comment I have solved the issue


您的工厂可能不应该是@Singleton。它是轻量级的,
不携带任何状态,并且您的视图模型可能绑定在
活动相关范围内,并且无论如何在@Singleton中都无法使用

Your factory probably shouldn't be @Singleton. It's lightweight, doesn't carry any state, and your viewmodels probably get bound in an activity related scope and aren't available in @Singleton anyways

我用 @Singleton 注释了工厂,该活动在活动范围中不可用。我刚刚删除了 @Singleton 批注。一切都按预期进行

I have annotated factory with @Singleton which cannot be available in activity scope. I have just removed the @Singleton annotation. Everything is working as expected

这篇关于错误[Dagger / MissingBinding]如果没有@Provides注释的方法,则无法提供androidx.lifecycle.ViewModelProvider.Factory的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆