gpt4 book ai didi

android - 为什么 Dagger 无法识别 AppModule 中的@Provides?

转载 作者:行者123 更新时间:2023-11-29 23:00:06 25 4
gpt4 key购买 nike

我收到这个错误:

[Dagger/MissingBinding] SessionFetcher cannot be provided without an @Inject constructor or an @Provides-annotated method. while you can see I have defined SessionFetcher

在 AppModule 类中


@Suppress("unused")
@Module
abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(AccountViewModel::class)
abstract fun bindAccountViewModel(accountViewModel: AccountViewModel): ViewModel

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

@Module(includes = [ViewModelModule::class])
class AppModule(private val applicationContext: Context) {

@Provides
fun sessionFetcher(@Named("UserPreferences") userPreferences: SharedPreferences): ISessionFetcher {
return SessionFetcher(userPreferences)
}

@Singleton
@Provides
@Named("UserPreferences")
fun userPreferences(context: Context): SharedPreferences {
return context.getSharedPreferences(USER_CONFIG_NAME, Context.MODE_PRIVATE)
}



class AccountViewModel @Inject constructor(sessionFetcher: SessionFetcher) :
SessionViewModel(sessionFetcher), AppComponent.Injectable {

最佳答案

您正在提供 ISessionFetcher在你的图表中,但你正在尝试 inject SessionFetcher 的实例.

您向图表提供的是您可以注入(inject)的类型。 Dagger 不分析 @Providing 的尸体函数(或最终实现类的类型)。


只需注入(inject)接口(interface)而不是实现类。

class AccountViewModel @Inject constructor(sessionFetcher: ISessionFetcher) :
SessionViewModel(sessionFetcher), AppComponent.Injectable {
//...
}

如果你需要使用SessionFetcher的方法ISessionFetcher 未公开的,然后是你的 ISessionFetcher 可能不完整。

关于android - 为什么 Dagger 无法识别 AppModule 中的@Provides?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57058569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com