如何在蛋糕模式中重用另一个组合中的依赖对象

时间:2016-12-06 06:41:00

标签: scala dependency-injection cake-pattern

我有两个服务类,如下...

用户服务:

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

集团服务:

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!")
  }
 }
 ...
}

我只是验证该组的所有者是否是有效用户。为此,我重复使用了带有硬编码Dao实现的userService.read方法,即UserMySqlDao 在这里,我的问题是不是提供硬编码的Dao Impl,而是如何使用groupservice的dao对象。因为UserService和GroupService的类型相同。

我尝试使用以下

val userService = new UserService with dao

但是失败了。我是scala的新手,因此不清楚为什么会失败。如果有人可以说明为什么这不合法,那将会很有帮助。

先谢谢:)

2 个答案:

答案 0 :(得分:1)

如果我理解你的问题,那么你正在寻找使用蛋糕模式进行多重依赖声明的解决方案。

常用的解决方案是定义一个新类型组件,它包含对所需所有依赖项的引用。在您的具体情况下,故事将如下。

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!")
      }
    }
  }
}

如果您需要更多信息,请与我们联系。

答案 1 :(得分:0)

只是觉得我玩得很开心,看看我能编译什么。不确定这是一个很好的解决方案,甚至不是好的风格,但我的想法是让GroupService依赖于UserService,这使得它公开了。

select(-newFlag)
相关问题