如果没有 @Provides 注释方法,则无法提供 Hilt

Hilt cannot be provided without an @Provides-annotated method

我有 activity

的视图模型
@HiltViewModel
class MainViewModel @Inject constructor(
private val repository: UserRepository
)     : ViewModel() {

}

存储库界面

interface UserRepository {
suspend fun loginUser(username: String, password: String): Pair<Boolean, String>
}

用户数据来源class如下

internal class UserDataSource @Inject constructor(private val octaveApi: OctaveApi) :
UserRepository {

override suspend fun loginUser(username: String, password: String): Pair<Boolean, String> {
    return Pair(false, "unsucess")
}
}

这是我的匕首实现

@Module
@InstallIn(SingletonComponent::class)
abstract class ApiModule {

  @Module
  @InstallIn(SingletonComponent::class)
  object Providers {

    @Provides
    @Singleton
    internal fun provideOctaveApi(retrofit: Retrofit): OctaveApi =
      retrofit.create(OctaveApi::class.java)
  }
}

@Module
@InstallIn(ActivityRetainedComponent::class)
abstract class RetainedDataModule {

  @Binds
  internal abstract fun bindUserRepository(userDataSource: UserDataSource):     UserRepository
}

当我构建项目时出现此错误

/OctaveDashboard/app/build/generated/source/kapt/stagingExternalDebug/com/octave/OctaveApplication_HiltComponents.java:125: error: [Dagger/MissingBinding] com.octave.data.user.UserRepository cannot be provided without an @Provides-annotated method.
  public abstract static class SingletonC implements OctaveApplication_GeneratedInjector,
                     ^
  com.octave.data.user.UserRepository is injected at
      com.octave.MainViewModel(cornersRepository)
  com.octave.MainViewModel is injected at
      com.octave.MainViewModel_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.octave.OctaveApplication_HiltComponents.SingletonC → com.octave.OctaveApplication_HiltComponents.ActivityRetainedC → com.octave.OctaveApplication_HiltComponents.ViewModelC]

似乎无法找出问题的原因。

我的应用程序模块中缺少模块依赖项,这导致了这个问题。能够通过包含它来修复。

将@Provides 添加到您的函数中

 internal class UserDataSource @Inject constructor(private val octaveApi: OctaveApi) :
UserRepository {

@Provides
override suspend fun loginUser(username: String, password: String): Pair<Boolean, String> {
    return Pair(false, "unsucess")
}
}