I'd like to define database calls in service methods, but have them executed in the context of a Transaction
class without opening the connection in the service itself so that I can include multiple service calls in the same transaction.
I'm looking for something like this, but can't quite figure it out.
class Transaction {
init { /** Grab connection **/ }
fun doSelect() { ... }
}
class UserService {
fun Transaction.getUser() {
return doSelect()
}
}
fun main (args: Array<String>) {
Transaction() {
UserService().getUser() // INVALID
...
}
}
Is there a way to do this?
I know that I can pass in a transaction instance to the service like so:
class UserService(tx: Transaction) {
fun getUser() {
with(tx) {
doSelect()
}
}
...
fun main (args: Array<String>) {
Transaction() {
UserService(this).getUser()
...
}
}
...but am hoping for a more elegant pattern.