没有名称引用的 koin 默认实现

koin default implementation without name reference

我有 2 个 Retrofit 客户端,其中一个是默认的,第二个有不同的实现,例如(基础 URL、拦截器等...)

我需要在不使用名称引用的情况下注入默认客户端

第一个客户:-

single<Retrofit> {
Retrofit.Builder()
        .baseUrl(RemoteConstants.BASE_URL)
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addConverterFactory(APIResponseConverter())
        .addConverterFactory(GsonConverterFactory.create(get()))
        .client(get())
        .build()
    }

第二个客户:-

single<Retrofit>("retrofit_second") {
        Retrofit.Builder()
                .baseUrl("diffrent url")
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(get()))
                .client(get("SecondOkHttpClient"))
                .build()
}

我的注射方式

val myModule = module {
    factory { get<Retrofit>().create(FirstAPI::class.java) } // Why Koin did not figure it without providing its default name !?
    factory { get<Retrofit>("retrofit_second").create(SecondAPI::class.java) }
    factory<IMyRemoteDataSource> { MyRemoteDataSource(get(), get()) }
    factory<IMyRepository> { MyRepository(get()) }
    factory { MyUseCase(get()) }
}

结果是:

        Multiple definitions found for type 'class retrofit2.Retrofit' - Koin can't choose between :
    Single [name='retrofit_second',class='retrofit2.Retrofit']
    Single [name='Retrofit',class='retrofit2.Retrofit']

为什么 Koin 在没有提供默认名称(Retrofit)的情况下没有获得默认的 Retrofit 实例!?

factory { get<Retrofit>().create(FirstAPI::class.java) }

你是对的@Eslam。当前行为(从 koin:1.0.2 开始)是当您未指定依赖项名称时,它是 treated as an empty string. And then the definitions get filtered by class name:

fun searchByClass(clazz: KClass<*>): List<BeanDefinition<*>> {
    return definitions.filter { clazz in it.classes }
}

结果你得到了你的两个定义,这导致了上面提到的错误:Multiple definitions for class ....