Search code examples
scaladependency-injectioncake-pattern

How reuse a dependency object in another composition in cake pattern


I have two service classes like below...

User Service:

class UserService { dao: UserGroupDao =>
 ...
 def read(userId: String): Future[Option[User]] = dao.readUser(userId)
 ...
}

Group Service:

class GroupService {dao: UserGroupDao =>
 def createGroup(group: Group): Future[Either[String, String]]) = {
  val userService = new UserService() with UserMysqlDao
  userService.read(group.ownerId) map {
   case Some(u) => dao.createGroup(group)
   case None => Left("Invalid User!")
  }
 }
 ...
}

I am just validating if the owner of the group is a valid user. For that I reused the userService.read method with a hardcoded Dao Implementation i.e. UserMySqlDao.
Here my question is instead of providing hardcoded Dao Impl how could I use the groupservice's dao object. because the type are same for UserService and GroupService.

I tried using the following

val userService = new UserService with dao

but this failed. I am new to scala hence, not really clear why this failed. It would be helpful if someone can put some light on why this is not legal.

Thanks in Advance :)


Solution

  • If I understand right your question, you're looking for a solution for multiple dependencies declaration using the Cake Pattern.

    The solution commonly used is to define a new type, a component, that contains references to all the dependencies that you need. In your specific case, the story will be the following.

    trait GroupServiceComponent {
      val userService: UserService
      val userGroupDao: UserGroupDao
    
      class GroupService {
        def createGroup(group: Group): Future[Either[String, String]]) = {
          userService.read(group.ownerId) map {
            case Some(u) => userGroupDao.createGroup(group)
            case None => Left("Invalid User!")
          }
        }
      }
    }
    

    Let me know if you need more information.