Does anyone have any examples of using Koin to inj...
# koin
a
Does anyone have any examples of using Koin to inject an exposed Database instance? or would that be a misuse? Decided to try kotlin (coming from scala, etc) yesterday and can't figure out how to use this library.
r
That's exactly what I'm doing in my project right now! It looks like this:
Copy code
@Suppress("RemoveExplicitTypeArguments")
val dbModule = module {
    // ...
    single<Database>(createOnStart = true) { connectToDb(get(), get()) }
   // ...
}

fun connectToDb(dbConfig: DBConfig, secrets: Secrets) =
    Database.connect(
        url = dbConfig.url,
        driver = dbConfig.driver,
        user = dbConfig.user,
        password = secrets[dbConfig.`password-secret`].value
    ).apply { if (dbConfig.`verify-on-start`) verify() }

fun Database.verify() = // Verification logic

data class DBConfig(
    val url: String,
    val driver: String,
    val user: String,
    val `password-secret`: String,
    val `verify-on-start`: Boolean
)
It's pretty straightforward, and works well for us so far
a
👍
a
Thanks for taking the time to show me that, but how do I then inject that into the constructor of a service and use it? I can't figure out how to actually make use of the definition
unless I have to extend the KoinComponent thing or w/e and inject like that
r
I exclusively do constructor injection, so the individual classes, services etc. don't have any knowledge of how I'm injecting then, and then I let Koin build the complete graph of services. It can look like this:
Copy code
val appModule = module {
    single<Database>() { // see above }
    single<Service>()
}

// use site:
val koin = startKoin(listOf(appModule))
val service = koin.koinContext.get<Service>()
You might have to replace
single<Service>()
with
single { Service(get()) }
if you don't want to use the experimental api that uses reflection in the background.
(This is assuming that
Service
is defined like
class Service(val db: Database)
)
a
Oh, good to know, thanks so much!
Looks great
Yeah that message just solved a couple hours of confusion and frustration, thanks so much!
r
Glad I could help!