koin - kotlin依赖注入框架

Koin是一款专为Kotlin设计的轻量级依赖注入框架,具备无代理、无代码生成、无反射的特点。本文介绍如何在Android项目中引入Koin依赖、声明依赖模块、配置应用程序上下文并实现依赖注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是koin?

koin 是一个用于kotlin的实用型轻量级依赖注入框架,采用纯kotlin编写而成,仅使用功能解析,无代理、无代码生成、无反射。

koin 是一个DSL,一个轻便的容易和一个使用的API。

用法 

1,添加依赖

// Add Jcenter to your repositories if needed
repositories {
    jcenter()    
}
dependencies {
    // Koin for Android
    compile 'org.koin:koin-android:0.9.3'
}

2,声名一个依赖

创建要给仓库来提供一些数据(giveHello()

interface Repository {
    fun giveHello()
}

class MyRepository() : Repository {
    override fun giveHello() = "Hello Koin"
}

创建一个Presenter类来消费数据:

// Use Repository - injected by constructor by Koin
class MyPresenter(val repository : Repository){
    fun sayHello() = repository.giveHello()
}

applicationContext方法来声名一个模块。

// Koin module
val myModule : Module = applicationContext {
    provide { MyPresenter(get()) } // get() will resolve Repository instance
    provide { MyRepository() as Repository }
}

3,开启Koin

再我们的Application中开启Koin

class MyApplication : Application(){
    override fun onCreate() {
        super.onCreate()
        // Start Koin
        startKoin(this, listOf(myModule))
    }
}

4,注入依赖

MyPresenter 和Presenter 实例一起创建。为了再Activity中使用,我们通过by inject()来注入它。

class MyActivity : AppCompatActivity(){

    // Inject MyPresenter
    val presenter : MyPresenter by inject()

    override fun onCreate() {
        super.onCreate()
        // Let's use our presenter
        Log.i("MyActivity","presenter : ${presenter.sayHello()}")
    }
}

by inject()方法允许我们在组件运行时(Activity, fragment, Service...)获取去Koin实例,

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值