使用蛋糕模式实现传递性依赖注入

5
我尝试使用蛋糕模式进行依赖注入,代码如下:

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。所以问题是:是否可能在RequiresFoo内部创建一个AlsoNeedsFoo对象,以便依赖注入正常工作?
1个回答

7
使用蛋糕模式时,您不应该实例化其他组件,而是应该扩展它们。
在您的情况下,如果需要 AlsoNeedsFoo 的功能,您应该编写类似以下内容的代码:
this: FooComponent with AlsoNeedsFoo with ... =>

并将所有内容放在顶层:

val app = MyImpl extends FooComponent with AlsoNeedsFoo with RequiresFoo with ...

4
这意味着无法在RequiresFoo中创建多个AlsoNeedsFoo的实例,是这样吗? - dratewka

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接