1

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.

geg
  • 4,399
  • 4
  • 34
  • 35
  • what is `Transaction() {...}`? I assume it is a function `fun Transaction(block: Transaction.() -> Unit)`, but you didn't define one. – voddan Mar 15 '16 at 06:45

1 Answers1

0

The system works the other way around, so to fix the issue, swap the receivers:

fun main (args: Array<String>) {
    UserService().apply {
        Transaction().getUser() 
    }
}
voddan
  • 31,956
  • 8
  • 77
  • 87