https://start.insert-koin.io/#/getting-started/koin-components

开始

Koin in 5 minutes (5分钟快速入手Koin)

Getting Started (开始)

有时不能仅通过Koin声明组件。依赖于你的运行时技术,你可能需要在一个不是用Koin创建的类中从Koin检索实例(例如Android)。

Koin组件实例

通过 KoinComponent 接口来标记你的类就能解锁Koin的注入功能:

  • by inject() - 延迟注入一个实例
  • get() - 检索一个实例
  • getProperty() - 获得一个Koin属性

我们可以将上面的模块注入到类属性中:

1
2
3
4
5
6
7
8
9
10
// Tag class with KoinComponent
class HelloApp : KoinComponent {

// lazy inject dependency
val helloService: HelloServiceImpl by inject()

fun sayHello(){
helloService.sayHello()
}
}

然后我们就只需要开启Koin并运行我们的类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// a module with our declared Koin dependencies 
val helloModule = module {
single { HelloServiceImpl() }
}

fun main(vararg args: String) {

// Start Koin
startKoin {
modules(helloModule)
}

// Run our Koin component
HelloApp().sayHello()
}

引导

KoinComponent 接口也能被用来协助你从Koin外部引导一个应用程序。另外,您可以通过扩展函数直接在一些目标类上引入“KoinComponent”特性(即:Android中的Activity、Fragment have KoinComponent特性)。

Bridge with Koin instance

KoinComponent 接口主要带来了如下内容:

1
2
3
4
5
6
7
interface KoinComponent {

/**
* Get the associated Koin instance
*/
fun getKoin(): Koin = GlobalContext.get().koin
}

他带来了如下的可能性:

然后可以重新定义 getKoin() 函数,以重定向到本地自定义Koin实例