MOCKSTACKS
EN
Questions And Answers

More Tutorials









Scala Dependency Injection

Examples

Cake Pattern with inner implementation class.


//create a component that will be injected
trait TimeUtil {
 lazy val timeUtil = new TimeUtilImpl()
 class TimeUtilImpl{
 def now() = new DateTime()
 }
}
//main controller is depended on time util
trait MainController {
 _ : TimeUtil => //inject time util into main controller
 lazy val mainController = new MainControllerImpl()
 class MainControllerImpl {
 def printCurrentTime() = println(timeUtil.now()) //timeUtil is injected from TimeUtil
trait
 }
}
object MainApp extends App {
 object app extends MainController
 with TimeUtil //wire all components
 app.mainController.printCurrentTime()
}

In the above example, I demonstrated how to inject TimeUtil into MainController.

The most important syntax is the self-annotation (_: TimeUtil =>) which is to inject TimeUtil into MainController. In another word, MainController depends on TimeUtil.

I use inner class (e.g. TimeUtilImpl) in each component because, in my opinion, that it is easier for testing as we can mock the inner class. And it is also easier for tracing where the method is called from when project grows more complex.

Lastly, I wire all component together. If you are familiar with Guice, this is equivalent to Binding

Conclusion

In this page (written and validated by ) you learned about Scala Dependency Injection . What's Next? If you are interested in completing Scala tutorial, your next topic will be learning about: Scala Dynamic Invocation.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.