Paulius Ruminas
05/29/2019, 2:03 PM// Register by KClass
private fun Module.single(
type: KClass<*>,
createdAtStart: Boolean = false,
override: Boolean = false
): BeanDefinition<*> {
val beanDefinition = BeanDefinition<Any>(
qualifier = null,
scopeName = null,
primaryType = type
).apply {
this.definition = {
val constructor = type.getFirstJavaConstructor()
val args = getArguments(constructor, this)
constructor.makeInstance(args)
}
this.kind = Kind.Single
}
declareDefinition(beanDefinition, Options(createdAtStart, override))
return beanDefinition
}
// Inject by KClass
private fun <T : Any> Application.inject(type: KClass<T>): Lazy<T> = lazy { getKoin().rootScope.get(type.java) }
// Module declaration
val myModule = module {
// findKClasses - returns List<KClass<*>>
findKClasses().forEach { single(it) }
}
We have classes that we need to resolve dynamically by KClass so that is why we need an ability to register them by KClass.
It works now but I wonder how much this code is prone to breaking changes in the future. Or is there an "official way" to achieve this?arnaud.giuliani
05/30/2019, 6:10 AMkoin=core-ext
extensions to declare a component without gaving to write a constructorarnaud.giuliani
05/30/2019, 6:10 AMPaulius Ruminas
05/30/2019, 7:08 AMarnaud.giuliani
05/30/2019, 7:09 AMPaulius Ruminas
05/30/2019, 7:10 AM