How to use Qualifiers with Assisted Injection?

Viewed 156

I would like to create a class where I can pass some runtime parameters as an input. To do so I can use Assisted Injection.

But I would also like to provide different implementations of this class depending on a Qualifier. Then I could have for instance 2 Assisted Factories that would provide different types.

When I try to create a @Provides method on a class that use Assisted Injection, I get this error: Dagger does not support providing @AssistedInject types.

Is there a way to achieve what I am trying to do with dagger?

This is the general idea of what I would like to have even if this code doesn't work:

class DependencyWithQualifier(val type: Int)
class OtherDependency

class SampleClass @AssistedInject constructor(
    @Assisted val name: String,
    val dependencyWithQualifier: DependencyWithQualifier,
    otherDependency: OtherDependency,
) {
    @AssistedFactory
    interface Type1Factory {
        @Named("type1")
        fun create(name: String): SampleClass
    }

    @AssistedFactory
    interface Type2Factory {
        @Named("type2")
        fun create(name: String): SampleClass
    }
}

@Module
@InstallIn(SingletonComponent::class)
class SampleClassModule {

    @Provides
    @Named("type1")
    fun provideType1SampleClass(
        name: String,
        otherDependency: OtherDependency
    ) = SampleClass(
        name = name,
        dependencyWithQualifier = DependencyWithQualifier(1),
        otherDependency = otherDependency
    )

    @Provides
    @Named("type2")
    fun provideType2SampleClass(
        name: String,
        otherDependency: OtherDependency
    ) = SampleClass(
        name = name,
        dependencyWithQualifier = DependencyWithQualifier(2),
        otherDependency = otherDependency
    )
}
0 Answers
Related