-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathexamples.scala
128 lines (106 loc) · 2.48 KB
/
examples.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package examples {
trait Configuration {
def value: String
}
class DefaultConfiguration extends Configuration {
val value = "production"
}
class TestingConfiguration extends Configuration {
val value = "test"
}
trait ConfigurationComponent {
val configuration: Configuration
}
}
package examples.example1 {
/**
* *
* Uses the cake pattern in scala to perform dependency injection.
*
* In this example B depends on Configuration and A and A depends
* on Configuration.
*
*/
import examples._
trait AComponent {
this: ConfigurationComponent =>
val a: A
class A {
val value = "a-" + configuration.value
}
}
trait BComponent {
this: ConfigurationComponent with AComponent =>
val b: B
class B {
val value = a.value + "-b-" + configuration.value
}
}
trait Components
extends ConfigurationComponent
with AComponent
with BComponent
object Registry extends Components {
val configuration = new DefaultConfiguration
val a = new A()
val b = new B()
}
object RegistryTesting extends Components {
val configuration = new TestingConfiguration
val a = new A()
val b = new B()
}
}
package examples.example2 {
/**
* *
* Uses the cake pattern in scala to perform dependency injection.
*
* In this example we build on example 1 providing A and B with different instances of C
* which is itself dependent on configuration.
*
* ```
* B -> Configuration
* -> A
* -> C
* A -> Configuration
* -> C (different instance)
* C -> Configuration
* ```
*/
import examples._
import java.util.UUID._
trait AComponent {
this: ConfigurationComponent with CComponent =>
val a: A
class A {
val c = new C()
val value = "a-" + configuration.value + "-" + c.value
}
}
trait BComponent {
this: ConfigurationComponent with AComponent with CComponent =>
val b: B
class B {
val c = new C()
val value = a.value + "-b-" + configuration.value + "-" + c.value
}
}
trait CComponent {
this: ConfigurationComponent =>
class C {
val value = "c-" + configuration.value + "-" +
randomUUID.toString.substring(1, 5)
}
}
trait Components
extends ConfigurationComponent
with AComponent
with BComponent
with CComponent
object Registry extends Components {
val configuration = new DefaultConfiguration
val a = new A()
val b = new B()
}
}