Nikolay Kulachenko
Nikolay Kulachenko

Reputation: 4874

Override dependencies in Dagger Module

There's a base module with common dependencies:

@Module
object CommonActivityModule {

    @JvmStatic
    @Provides
    fun baseNavigator(activity: AppCompatActivity): Navigator = BaseNavigator(activity, SOME_STUFF)

    // other common deps
}

I include it in every Activity module to obtain those common deps. But in some modules I want to shadow a few base interface implementations with another:

@Module(includes = [CommonActivityModule::class])
interface SomeActivityModule {

    @Binds
    fun anotherNavigator(anotherNavigator: AnotherNavigator): Navigator    

    // other module's binds
}

And it thows ..Navigator is bound multiple times-exception. Is there a way how I can replace those interface implementations without dropping the whole CommonActivityModule?

Upvotes: 2

Views: 907

Answers (1)

AutonomousApps
AutonomousApps

Reputation: 4389

You're binding each as Navigator. I believe you need to use a different return type on your shadowed binding.

Alternatively, you could try something with Qualifiers. Defining a custom qualifier is easy; you should be able to find examples online. I'd share one, but I'm on my phone right now.

This answer has been accepted, so I'd like to add some code to make it more "complete". Here's an example of a custom "Qualifier" (Kotlin)

import javax.inject.Qualifier

@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class DelayQualifier

Usage:

@Module object {
    @Provides @DelayQualifier @JvmStatic
    fun provideDelay(): Long = if (BuildConfig.DEBUG) 1L else 3L
}

@ActivityScoped
class SignupViewModelFactory @Inject constructor(
    @param:DelayQualifier private val delay: Long
) : ViewModelProvider.Factory { ... }

This is the only Long I'm currently injecting in my project, so I don't need the qualifier. But if I decide I want more Longs, I'll regret not qualifying this one.

Upvotes: 1

Related Questions