Closed bj0 closed 5 years ago
Hello, to retrieve instances from Koin you have to use KoinComponent
interface.
Try something like:
val guice = Guice.createInjector(MyModule())
FX.dicontainer = object : DIContainer, KoinComponent {
override fun <T : Any> getInstance(type: KClass<T>)
= get()
}
When I try that, it gives "type inference failed". If I specify the return type as T
:
override fun <T : Any> getInstance(type: KClass<T>): T = get()
Then i get the error "cannot use T as reified type parameter. Use a class instead."
because you need to specify it in your signature: override inline fun <reified T : Any> getInstance(type: KClass<T>): T = get()
add the Kotlin keywords reified
and inline
.
both reified
and inline
give errors when used with override
.
Because we can't modify the overriden function signature. Let me open a bit this
fyi, I was able to get it to work with:
FX.dicontainer = object : DIContainer, KoinComponent {
override fun <T : Any> getInstance(type: KClass<T>): T = (StandAloneContext.koinContext as KoinContext).get(
ClassRequest(clazz = type.java, parameters = emptyParameterDefinition())
)
}
but it's ugly. It would be much nicer if there was an override of get
that just took the type, so I could just:
FX.dicontainer = object : DIContainer, KoinComponent {
override fun <T : Any> getInstance(type: KClass<T>): T = koinContext.get(type)
)
}
Cool 👍
Since beta-8
, it should be easier to write with (StandAloneContext.koinContext as KoinContext).getForClass(...)
arnaudgiuliani, can you provide an example please?
oops, nevermind. seems like this one worked for me
StandAloneContext.startKoin(listOf(appModule))
FX.dicontainer = object : DIContainer, KoinComponent {
override fun <T : Any> getInstance(type: KClass<T>): T =
(StandAloneContext.koinContext as KoinContext).getForClass(clazzName = type.qualifiedName!!)
}
val appModule = module {
single<StudioProjectModel>()
}
Good 👍
It looks like getForClass
disappeared in 1.0.0, is there a replacement?
Just use the get
function. It can get a KClass as parameter.
It took some trial and error to realize that I had to call one of the get
overloads on Koin
, as opposed to any on KoinComponent
. Here's how I got it to work with 2.0.1 in case it saves anyone some time:
FX.dicontainer = object : DIContainer, KoinComponent {
override fun <T : Any> getInstance(type: KClass<T>): T {
return getKoin().get(clazz = type, qualifier = null, parameters = null)
}
}
According to the tornadofx documentation: [https://edvin.gitbooks.io/tornadofx-guide/content/part2/Dependency%20Injection.html], you can override their basic DI with a 3rd party framework by setting:
I would like to use Koin, but I cannot find anything equivalent to
getInstance
in the Koin documentation.