【问题标题】:Dependency injection with Koin使用 Koin 进行依赖注入
【发布时间】:2018-12-03 10:50:45
【问题描述】:

我有一个使用 Dagger 2 进行依赖注入的类。现在我想切换到 Koin 进行依赖注入。 Koin 中有模块,我想在课堂之外制作一个模块或任何可以做的事情。

@Module
class NetModule(private val baseUrl: String) {

@Provides
@Singleton
fun providesOkHttpClient(
        httpLoggingInterceptor: HttpLoggingInterceptor): OkHttpClient = OkHttpClient.Builder().addInterceptor(
        httpLoggingInterceptor).build()

@Provides
@Singleton
fun provideLoggingInterceptor(): HttpLoggingInterceptor {
    val interceptor = HttpLoggingInterceptor(
            HttpLoggingInterceptor.Logger { message -> Logger.d("NETWORK: $message") })
    interceptor.level = HttpLoggingInterceptor.Level.NONE
    return interceptor
}

@Provides
@Singleton
fun providesMoshi(): Moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()

@Provides
@Singleton
fun providesRetrofit(okHttpClient: OkHttpClient, moshi: Moshi): Retrofit {
    return Builder().client(okHttpClient).baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
}

@Provides
@Singleton
fun providesApiInterface(retrofit: Retrofit): ApiInterface = retrofit.create(
        ApiInterface::class.java)
}

【问题讨论】:

标签: android kotlin koin


【解决方案1】:

Koin 使用 DSL 来描述模块。通常你会在顶层声明模块本身。由于您需要提供baseUrl,因此您必须为其创建一个工厂。

@Provides 注释是完全不相关的,但 @Singleton 需要翻译,并使用 single 进行翻译。要检索依赖项,只需调用get()。

fun netModule(baseUrl: String) = module {

    single {
        HttpLoggingInterceptor(
            HttpLoggingInterceptor.Logger { message ->
                Logger.d("NETWORK: $message")
        }).apply {
            level = HttpLoggingInterceptor.Level.NONE
        }
    }

    single {
        OkHttpClient.Builder()
            .addInterceptor(get<HttpLoggingInterceptor>())
            .build()
    }


    single {
        Moshi.Builder()
            .add(KotlinJsonAdapterFactory())
            .build()
    }

    single {
        Retrofit.Builder()
            .client(get())
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
    }

    single { get<Retrofit>().create(ApiInterface::class.java) }    
}

【讨论】:

  • 你是国王。!!
  • 我已经这样做了,但是由于声誉较低,它没有将其显示为已接受的答案。
  • @AbhishekDubey 接受答案不应该有声誉限制。只有upvoting 需要你有15 的声望。看看How does accepting an answer work? 你会在那里找到一个很好的解释。
  • 谢谢@tynn 我明白了,我已经这样做了。我之前不知道,谢谢提及。
  • 如果您有任何疑问,请查看完整文档@AbhishekDubey insert-koin.io/docs/2.0/documentation/reference/index.html 在那里您可以看到很多关于 Koin 工作原理的示例。
猜你喜欢
  • 1970-01-01
  • 2023-01-30
  • 2015-09-26
  • 2014-01-19
  • 2014-03-25
  • 2019-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多