传递DI使用蛋糕模式

时间:2014-02-24 12:14:49

标签: scala cake-pattern

我正在尝试使用像这样的蛋糕模式进行依赖注入:

trait FooComponent {
  val foo: Foo

  trait Foo;
}

trait AlsoNeedsFoo {
  this: FooComponent =>
}

trait RequiresFoo {
  this: FooComponent =>

  val a = new AlsoNeedsFoo with FooComponent{
    val foo: this.type#Foo = RequiresFoo.this.foo
  }

}

但是编译器抱怨RequiresFoo.this.type#Foo不符合预期的类型this.type#Foo

所以问题是:是否可以在AlsoNeedsFoo中创建一个RequiresFoo对象,以便依赖注入正常工作?

1 个答案:

答案 0 :(得分:7)

使用蛋糕模式,您不应该实例化其他组件,而是扩展它们。

在您的情况下,如果您需要AlsoNeedsFoo的功能,您应该写下这样的内容:

this: FooComponent with AlsoNeedsFoo with ... =>

并将所有内容放在最顶层:

val app = MyImpl extends FooComponent with AlsoNeedsFoo with RequiresFoo with ...
相关问题