In this post I would like to make small introduction to Scaldi and show you how easy it is to use it together with Play. Scaldi is dependency injection library for Scala. It’s very lightweight (without any dependencies) and provides nice Scala DSL for binding dependencies and injecting them. It’s more dynamic approach to do dependency injection in comparison to the cake pattern, because not everything is checked at the compile time. This can be seen as an disadvantage, but I personally believe, that there is place for this approach. It can be vary useful in many circumstances and many people can find it more natural (and easy), especially if they are coming from Java background.
There are only 3 most important traits that you need to know, in order to make dependency injection with Scaldi:
- Injector - it’s a container for the bindings, that you have defined in the module.
- Module - gives you nice syntax to create bindings with
Injectortrait and implicit
Injectorinstance always available when you are defining your bindings
- Injectable - the only responsibility of this trait is to provide you with
injectfunction (so it just provides nice syntax for injecting dependencies). It’s important to understand, that it’s the only the purpose of it. So it completely stateless and knows nothing about actual bindings you have defined in the module. In order to actually find and inject dependencies,
injectfunction always takes an implicit parameter of type