evant / kotlin-inject

Dependency injection lib for kotlin
Apache License 2.0
1.24k stars 55 forks source link

The order of dependencies with `@Qualifier` annotation modifies the scope of the dependency. #424

Closed AdriaBosch closed 2 weeks ago

AdriaBosch commented 1 month ago

I have found the following behavior related to scopes and @Qualifier annotation. Suppose we have the component:

@Scope
annotation class Singleton

@Qualifier
annotation class FirstClient

@Qualifier
annotation class SecondClient

interface ClientComponent {

    @Singleton
    @Provides
    @FirstClient
    fun provideFirstClient(): HttpClient {
        return HttpClient()
    }

    @Singleton
    @Provides
    @SecondClient
    fun provideSecondClient(
        @FirstClient
        firstClient: HttpClient,
    ): HttpClient {
        return firstClient.newBuilder().build()
    }
}

If we create this Api class with this particular order of dependencies

@Inject
class Api(
    @SecondClient
    val secondClient: HttpClient,

    @FirstClient
    val firstClient: HttpClient,
)

then FirstClient is not scoped and two instances are created. On the other hand if we create the same class but with different dependency order:

@Inject
class Api(
    @FirstClient
    val firstClient: HttpClient,

    @SecondClient
    val secondClient: HttpClient,
)

then FirstClient gets its scope and only one instance is created.