首页 > 解决方案 > 是否可以创建同一对象的不同实例并通过将参数传递给 Koin 中的 get() 函数来访问它们?

问题描述

我正在使用 Koin 作为我的应用程序的 DI。我创建了一个模块:

object NetworkModule {
    fun get() = module {
        single {
            val authenticationInterceptor = Interceptor { chain ->
                // Request customization goes here
            }

            OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .addInterceptor(authenticationInterceptor) //Not all clients might have this interceptor
                .build()
        }

        single {
            Retrofit.Builder()
                .baseUrl("example.com")
                .client(get(/* I would like to send some paramter here */))
                .addConverterFactory(GsonConverterFactory.create(get()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
                .create(Api::class.java)
        }
    } 
}

如何创建具有不同参数集HttpClientRetrofit具有不同实例化的不同实例?例如,在某些情况下,我可能需要OkHttpClient使用它,AutheniticationInterceptor而在另一些情况下,我的客户可能不需要使用它。

我可以在调用时传递一些参数,get()以便获得不同的实例吗?任何建议都会受到重视。

标签: androidkotlindependency-injectionkoin

解决方案


您可以使用命名属性 - 例如

single<OkHttpClient>(named("auth")){
// here you pass the version with authinterceptor
}
single<OkHttpClient>(named("noAuth")){
// here you pass the version without authinterceptor
}

然后在您的 get() 方法中传递名称,例如

.client(get(named("auth")))

推荐阅读