Koin Component
Koin은 module 및 definition을 설명하는 데 도움이 되는 DSL이며, definition를 확인하는 container입니다.
Koin Component는 container 외부에서 인스턴스를 검색하는 API입니다.
KoinComponent 인터페이스는 Koin에서 직접 인스턴스를 검색하는 데 도움이 됩니다.
주의! 클래스가 Koin container API에 연결됩니다.
module에서 선언할 수 있는 클래스에서는 사용하지 않고, 생성자 주입을 선호
즉, 최종적으로 생성자 주입이 아닌 필드주입을 해야하는 클래스에서 Koin Componet 인터페이스를 구현한다.
Create a Koin Component
클래스에 Koin 기능을 사용할 수 있는 기능을 제공하려면 KoinComponent 인터페이스로 태그를 지정해야 합니다.
class MyService
val myModule = module {
// Define a singleton for MyService
single { MyService() }
}
코인 컨테이너에서 인스턴스를 검색하기 위해 MyComponent를 작성하는 방법입니다.
fun main(vararg args : String){
// Start Koin
startKoin {
modules(myModule)
}
// Create MyComponent instance and inject from Koin container
MyComponent()
}
get() 및 inject()를 사용하여 MyService 인스턴스를 주입
class MyComponent : KoinComponent {
// lazy inject Koin instance
val myService : MyService by inject()
// or
// eager inject Koin instance
val myService : MyService = get()
}
Unlock the Koin API with KoinComponents
inject() - 코인 컨테이너에서 lazy 된 인스턴스
get() - 코인 컨테이너에서 즉시 가져오기 인스턴스
getProperty()/setProperty() - 게터 / 셋터
Retrieving definitions with get & inject
코인은 코인 컨테이너에서 인스턴스를 검색하는 두 가지 방법을 제공
val t : T by inject() - lazy 된 인스턴스
val t : T = get() - 즉시 액세스
Resolving instance from its name
필요한 경우 get() 또는 injection()을 사용하여 매개변수를 지정할 수 있습니다.
한정자 - definition의 이름(definition에 이름 매개변수가 지정된 경우)
val module = module {
single(named("A")) { ComponentA() }
single(named("B")) { ComponentB(get()) }
}
class ComponentA
class ComponentB(val componentA: ComponentA)
// retrieve from given module
val a = get<ComponentA>(named("A"))