@@ -65,6 +65,8 @@ end Providers
65
65
Explicit ().test()
66
66
println(s " \n Injected " )
67
67
Injected ().test()
68
+ println(s " \n Injected2 " )
69
+ Injected2 ().test()
68
70
69
71
/** Demonstrator for explicit dependency construction */
70
72
class Explicit :
@@ -173,5 +175,55 @@ class Injected:
173
175
end explicit
174
176
end Injected
175
177
178
+ /** Injected with builders in companion objects */
179
+ class Injected2 :
180
+ import Providers .*
181
+
182
+ case class User (name : String , email : String )
183
+
184
+ class UserSubscription (emailService : EmailService , db : UserDatabase ):
185
+ def subscribe (user : User ) =
186
+ emailService.email(user)
187
+ db.insert(user)
188
+ object UserSubscription :
189
+ def apply ()(using Provider [(EmailService , UserDatabase )]): UserSubscription =
190
+ new UserSubscription (provided[EmailService ], provided[UserDatabase ])
191
+
192
+ class EmailService :
193
+ def email (user : User ) =
194
+ println(s " You've just been subscribed to RockTheJVM. Welcome, ${user.name}" )
195
+
196
+ class UserDatabase (pool : ConnectionPool ):
197
+ def insert (user : User ) =
198
+ pool.get().runQuery(s " insert into subscribers(name, email) values ${user.name} ${user.email}" )
199
+ object UserDatabase :
200
+ def apply ()(using Provider [(ConnectionPool )]): UserDatabase =
201
+ new UserDatabase (provided[ConnectionPool ])
202
+
203
+ class ConnectionPool (n : Int ):
204
+ def get (): Connection =
205
+ println(s " Acquired connection " )
206
+ Connection ()
207
+
208
+ class Connection ():
209
+ def runQuery (query : String ): Unit =
210
+ println(s " Executing query: $query" )
211
+
212
+ def test () =
213
+ given Provider [EmailService ] = provide(EmailService ())
214
+ given Provider [ConnectionPool ] = provide(ConnectionPool (10 ))
215
+ given Provider [UserDatabase ] = provide(UserDatabase ())
216
+ given Provider [UserSubscription ] = provide(UserSubscription ())
217
+
218
+ def subscribe (user : User )(using Provider [UserSubscription ]) =
219
+ val sub = UserSubscription ()
220
+ sub.subscribe(user)
221
+
222
+ subscribe(
User (
" Daniel" ,
" [email protected] " ))
223
+ subscribe(
User (
" Martin" ,
" [email protected] " ))
224
+ end test
225
+ end Injected2
226
+
227
+
176
228
177
229
0 commit comments