簡體   English   中英

Koin依賴注入

[英]Dependency injection with Koin

我有一個使用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)
}

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) }    
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM