Hi everyone :wave: I started using ktor dependecy...
# ktor
j
Hi everyone ๐Ÿ‘‹ I started using ktor dependecy injection and I'm wondering if there is a way to access the application configuration using the
@Property
annotation when using basic dependency registration? I cannot seem to get it to work, so I was wondering if this only works in configuration-based dependency registration. Would be very nice to have a convenient way to access the config when using basic registration.
โž• 1
b
Looks like this only works for loading items from configuration references and class references. Lambdas and function references won't infer the parameter annotations. Could you specify how you're trying to use it now and I can log a ticket to address?
j
Thanks for the reply, Bruce! I'm currently doing something like this:
Copy code
fun Application.main() {
    databaseModule()
    //... other modules
}
where
databaseModule
is definded like this:
Copy code
fun Application.databaseModule() {
    val databaseUrl = environment.config.property("database.url").getString()
    dependencies {
        provide {
            provideDatabase(databaseUrl)
        }
    }
}

fun provideDatabase(databaseUrl: String): Database {
    val config = HikariConfig().apply {
        jdbcUrl = databaseUrl
        driverClassName = "org.postgresql.Driver"
        maximumPoolSize = 10
    }

    val datasource = HikariDataSource(config)

    Database.connect(datasource = datasource)
}
I'd love to be able to define it like this:
Copy code
fun Application.databaseModule() {
    dependencies {
        provide(::provideDatabase)
    }
}

fun provideDatabase(@Property("database.url") databaseUrl: String): Database {
    val config = HikariConfig().apply {
        jdbcUrl = databaseUrl
        driverClassName = "org.postgresql.Driver"
        maximumPoolSize = 10
    }

    val datasource = HikariDataSource(config)

    Database.connect(datasource = datasource)
}
It should be possible since
dependencies
are defined within the scope of
Application
where the config is available, but I don't know the implementation details of ktor di.
j
What if you made if
fun Application.provideDatabase
instead?
b
Yeah that seems like a reasonable expectation. We just implemented function references as lambdas so there's no reflection there to check parameter annotations. Best I can do for you atm is:
Copy code
fun Application.dbModule() {
   dependencies {
       provide { provideDatabase(property("database.url")) }
    }
}
You can also use @Property for module parameters if you're referencing them from a config file
j
Thanks for the update, Bruce! I'll go with the
property
shorthand ๐Ÿ‘
๐Ÿ™Œ 1
b
I've added a ticket to follow for introducing support for function references in code https://youtrack.jetbrains.com/issue/KTOR-8914/Dependency-inection-read-annotations-in-function-references ๐Ÿ‘€
๐Ÿ‘ 1
j
Great! Thank you so much for the support. Been enjoying using ktor very much.
๐Ÿ™‡ 1