使用Dagger2

时间:2018-03-20 19:44:53

标签: android dagger-2 android-architecture-components dagger

我正在使用Dagger2和新的Architecture Components构建Android应用程序。我在本教程后尝试使ViewModels可注入:https://blog.kotlin-academy.com/understanding-dagger-2-multibindings-viewmodel-8418eb372848

当我运行我的代码时,我收到以下错误:

[AndroidInjector.inject(T) Map<Class<? extends ViewModel>, Provider<ViewModel>> cannot be provided without an @Provides-annotated method.

我的代码如下所示:

@Singleton
class ViewModelFactory @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.asIterable().firstOrNull { modelClass.isAssignableFrom(it.key) }?.value
                ?: throw IllegalArgumentException("Unknown model class $modelClass")

        return creator.get() as T
    }
}

@Module
abstract class ViewModelFactoryModule {

    @Binds
    abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory
}

@MapKey
@Target(FUNCTION, PROPERTY_GETTER, PROPERTY_SETTER)
annotation class ViewModelKey(val value: KClass<out ViewModel>)

我的模块也包含在AppComponent中:

@Singleton
@Component(modules = [
    AndroidSupportInjectionModule::class,
    ViewModelFactoryModule::class // ...
])
interface AppComponent : AndroidInjector<BaseApplication>

class BaseApplication : DaggerApplication(), HasActivityInjector {

    override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
        return DaggerAppComponent.builder().appModule(AppModule(this)).build()
    }

我尝试注入的ViewModel在模块中声明如下:

@Module
abstract class SettingsModule {

    @Binds
    @IntoMap
    @ViewModelKey(SettingsViewModel::class)
    abstract fun bindSettingsViewModel(model: SettingsViewModel): ViewModel
}

有人知道问题可能是什么吗?

1 个答案:

答案 0 :(得分:1)

很难指出Dagger的确切问题。尝试移动

@Binds
@IntoMap
@ViewModelKey(SettingsViewModel::class)
abstract fun bindSettingsViewModel(model: SettingsViewModel): ViewModel

SettingsModuleViewModelFactoryModule,因为我在我的代码库中正在做的事情并且它正在发挥作用。

@Module
abstract class ViewModelFactoryModule {

    @Binds
    abstract fun bindViewModelFactory(factory: ViewModelFactory): 
                                      ViewModelProvider.Factory
}

OR

尝试将ViewModelKey更改为:

@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
@Retention(AnnotationRetention.RUNTIME)
@MapKey
annotation class ViewModelKey(val value: KClass<out ViewModel>)