Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transitive DI using cake pattern

I'm trying to do dependency injection using the cake pattern like so:

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
  }

}

but the compiler complains that the RequiresFoo.this.type#Foo doesn't conform to the expected type this.type#Foo.

So the question: is it possible to create a AlsoNeedsFoo object inside RequiresFoo so that dependency injection works properly?

like image 608
dratewka Avatar asked Feb 24 '14 12:02

dratewka


People also ask

What is the cake pattern?

It's called the Cake pattern, a sort of dependency injection mechanism that uses only idiomatic Scala constructs. The cake pattern represents the most important use of the self-type annotation in Scala. The pattern defines two different aspects of dependency management. The first is how to declare a dependency.

Is DI a design pattern?

Dependency Injection (DI) is a design pattern used to implement IoC. It allows the creation of dependent objects outside of a class and provides those objects to a class through different ways.

How do you implement DI?

The recommended way to implement DI is, you should use DI containers. If you compose an application without a DI CONTAINER, it is like a POOR MAN'S DI . If you want to implement DI within your ASP.NET MVC application using a DI container, please do refer to Dependency Injection in ASP.NET MVC using Unity IoC Container.


1 Answers

With cake pattern you should not instantiate other components, but extends them.

In your case you if you need functionality of AlsoNeedsFoo you should write something like this:

this: FooComponent with AlsoNeedsFoo with ... =>

And put all together on top level:

val app = MyImpl extends FooComponent with AlsoNeedsFoo with RequiresFoo with ...
like image 163
1esha Avatar answered Oct 07 '22 17:10

1esha