应用程序
@HiltAndroidApp
class MyApplication : Application()
模块
@Module
@InstallIn(ActivityComponent::class, FragmentComponent::class)
class ApplicationModule {
@Provides
fun provideService(): Service = ServiceImpl()
}
碎片
@AndroidEntryPoint
class MyFragment: Fragment() {
@Inject lateinit var service: Service
}
到目前为止一切正常,现在我尝试创建一个ViewModel并将服务移动到ViewModel 中
ViewModel
@HiltViewModel
class WinnersViewModel @Inject constructor(
private val service: Service
) : ViewModel()
更新的片段
@AndroidEntryPoint
class MyFragment: Fragment() {
private val viewModel: WinnersViewModel by viewModels()
}
在这一点上,我开始得到编译错误
/Users/user/Desktop/Repos/App/Android/app/build/generated/source/kapt/debug/com/app/Application_HiltComponents.java:124: error: [Dagger/MissingBinding] com.comp.app.services.Service cannot be provided without an @Provides-annotated method.
public abstract static class SingletonC implements Application_GeneratedInjector,
^
com.comp.app.services.Service is injected at
com.comp.app.winners.WinnersViewModel(service)
com.comp.app.winners.WinnersViewModel is injected at
com.comp.app.winners.WinnersViewModel_HiltModules.BindsModule.binds(vm)
@dagger.hilt.android.internal.lifecycle.HiltViewModelMap java.util.Map<java.lang.String,javax.inject.Provider<androidx.lifecycle.ViewModel>> is requested at
dagger.hilt.android.internal.lifecycle.HiltViewModelFactory.ViewModelFactoriesEntryPoint.getHiltViewModelMap() [com.comp.app.Application_HiltComponents.SingletonC → com.comp.app.Application_HiltComponents.ActivityRetainedC → com.comp.app.Application_HiltComponents.ViewModelC]
知道问题出在哪里吗?
您必须在模块中选择SingletonComponent,如下所示:
@Module
@InstallIn(SingletonComponent::class)
class ApplicationModule {
@Provides
fun provideService(): Service = ServiceImpl()
}