使用 Koin 进行依赖注入

Dependency injection with Koin

我有一个 class 使用 Dagger 2 进行依赖注入。现在我想切换到 Koin 进行依赖注入。 Koin 中有模块,我想用 class 或任何可以做的东西制作一个模块。

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