Hello, I just started using koin in ktor project ...
# koin
p
Hello, I just started using koin in ktor project and I added additional functionality to allow registration of singleton by KClass argument e.g.:
Copy code
// 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?
a
in Ktor you can use the
koin=core-ext
extensions to declare a component without gaving to write a constructor
p
All of these functions use reified type parameter. If I use classgraph library to search for classes I don't have that information at compile time so I can't use any of these functions.
a
ok I see your issue
p
https://github.com/InsertKoinIO/koin/issues/475 I created an issue with a little bit more information.
👍 1