Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Scala CAKE / Component Based Dependency Injection

CAKE / Component Based Dependency Injection

Simple

Simple Repository

trait ARepositoryComponent {
  protected def aRepository: ARepository

  protected trait ARepository {
    def findAll: List[A]
    def save(a: A): Unit
  }
}

trait ARepositoryComponentImpl extends ARepositoryComponent {
  override protected val aRepository: ARepository = new ARepositoryImpl

  private[this] class ARepositoryImpl extends ARepository {
    override def findAll() = List[A]()
    override def save(a: A) = println("TODO create " + a)
  }
}

Simple Service

trait AServiceComponent { self: ARepositoryComponent =>
  protected def aService: AService

  protected trait AService {
    def create(foo: String, bar: String): Unit
  }
}

trait AServiceComponentImpl extends AServiceComponent { self: ARepositoryComponent =>
  override protected val aService: AService = new AServiceImpl

  private[this] class AServiceImpl extends AService {
    override def create(foo: String, bar: String) =
      aRepository.save(A(foo, bar))
  }
}

Repository: Seperating 'Locator' (read/find) and 'Updater' (write) functionality

trait ARepositoryComponent {
  protected def aLocator: ALocator
  protected def aUpdater: AUpdater

  protected trait ALocator {
    def findAll: List[A]
  }
  protected trait AUpdater {
    def save(a: A)
  }
}

trait ARepositoryComponentImpl extends ARepositoryComponent {
  protected def aLocator: ALocator = new ALocatorImpl
  protected def aUpdater: AUpdater = new AUpdaterImpl

  private[this] class ALocatorImpl {
    override def findAll = List[A]()
  }
  private[this] class AUpdaterImpl {
    override def save(a: A) = println("TODO create " + a)
  }
}

Generic Locator/Updater

trait GenericLocator[T] {
  def findAll: List[T]
}

trait GenericUpdater[T] {
  def save(model: T)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment