【问题标题】:Error [Dagger/MissingBinding] androidx.lifecycle.ViewModelProvider.Factory cannot be provided without an @Provides-annotated method错误 [Dagger/MissingBinding] androidx.lifecycle.ViewModelProvider.Factory 不能在没有 @Provides-annotated 方法的情况下提供
【发布时间】:2019-11-06 08:11:32
【问题描述】:

我在使用 dagger 2.2 实现 MultiBinding 时遇到问题。我正在使用带有 MVVM 架构的匕首。我已经注入了ViewModelProvideFactory 构造函数并绑定了模块的依赖。

我已经按照 youtube 上 Mitch 的教程学习了

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

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

Dagger2: ViewModel cannot be provided without an @Provides-annotated method

Dagger/MissingBinding java.util.Map<java.lang.Class<? extends ViewModel>,Provider<ViewModel>> cannot be provided without an @Provides-annotated method

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"
    }
}

堆栈跟踪

> 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 版本,但仍然面临同样的问题。告诉我什么,我做错了吗?

编辑 1

我还通过活动范围内的 AuthViewModel 提供 ViewModel。当 Activity 销毁其组件并且依赖项也会销毁。

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();
}

【问题讨论】:

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

标签: android kotlin dependency-injection dagger-2 dagger


【解决方案1】:

根据评论我已经解决了问题

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

我用 @Singleton 注释了工厂,这在活动范围内不可用。我刚刚删除了@Singleton 注释。一切都按预期工作

【讨论】:

  • 你救了我!我试图找到这个问题几个小时......非常感谢。
【解决方案2】:

您需要为您的视图模型添加提供注释的方法,见下文。

@SuppressWarnings("unused")
@Binds
@IntoMap
@ViewModelKey(value = SomeViewModel.class)
abstract ViewModel bindSomeViewModel(SomeViewModel viewModel);


@SuppressWarnings("unused")
@Binds
abstract ViewModelProvider.Factory bindViewModelFactory(ViewModelFactory viewModelFactory);

【讨论】:

  • 能否提供详细代码。我们在哪里提供这个。
猜你喜欢
  • 2021-05-05
  • 2021-06-11
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 2020-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多