Home > OS >  error: [Dagger/DuplicateBindings] ... is bound multiple times:
error: [Dagger/DuplicateBindings] ... is bound multiple times:

Time:09-17

Trying to set up DI with a project I'm working on (one module per layer app), and I've ran into an issue that I don't know how to fix:

  public abstract static class SingletonC implements FragmentGetContextFix.FragmentGetContextFixEntryPoint,
                         ^
      @Singleton @Provides @org.jetbrains.annotations.NotNull winged.example.data.DoggoApi winged.example.data.di.DataModule.provideDoggoApi()
      @Singleton @Provides @org.jetbrains.annotations.NotNull winged.example.data.DoggoApi winged.example.modularretrofitapp.NetworkingModule.provideDoggoApi(okhttp3.OkHttpClient)
      winged.example.data.DoggoApi is injected at
          winged.example.data.di.DataModule.provideRepository(api)
      winged.example.domain.repository.DoggoRepository is injected at
          winged.example.presentation.doggoFragment.DoggoFragmentViewModel(repository)
      winged.example.presentation.doggoFragment.DoggoFragmentViewModel is injected at
          winged.example.presentation.doggoFragment.DoggoFragmentViewModel_HiltModules.BindsModule.binds(arg0)
      @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.ViewModelFac

The project structure is as follows:

  1. Application class in the app module:
@HiltAndroidApp
class DoggoApp: Application()

which is referenced in the manifest android:name=".DoggoApp"

  1. in the data module I have declared a hilt module:
@Module
@InstallIn(SingletonComponent::class)
object DataModule {
    @Singleton
    @Provides
    fun provideDoggoApi(): DoggoApi {
        return Retrofit.Builder()
            .baseUrl("https://dog.ceo/")
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
            .create(DoggoApi::class.java)
    }

    @Provides
    fun provideRepository(api: DoggoApi): DoggoRepository {
        return DoggoRepositoryImpl(api)
    }
}

and this is later injected into a view model which currently looks like this:

@HiltViewModel
class DoggoFragmentViewModel @Inject constructor(private val repository: DoggoRepository): ViewModel() {
    fun makeRequest() {
        repository.getRandomDoggo()
    }
}

what changes should I make to fix it? any links/hints/answers will be appreciated :)

CodePudding user response:

It seems you are providing DoggoApi in two different modules, DataModule and NetworkingModule. You should have only one provider for a type in SingletonComponent, So you need to separate them using Qualifiers or remove either the provider in DataModule or NetworkingModule

  • Related