Julien Richard-Foy’s blog

Dependency injection in Scala with Play 2: it’s free

When you write a software you generally split it into several modules with no hardcoded dependencies between them so you can reuse and test them more easily: you just need to wire the different modules together at startup according to your desired configuration.

In the Java world, some tools help to perform the wiring task, e.g. Spring or Guice, but in Scala you can perform dependency injection without having to rely on an external tool, as you’ll see in this post where I’ll show how to apply the Cake pattern in the context of a Play 2 application.

An example of use case where you may want to use a dependency injection mechanism is when you write a web application which needs the user to be authenticated to perform some actions. During development time it’s generally more comfortable to bypass the authentication step (when you just want to quickly test features you are coding right now). Thus, you want to have two authentication strategies: one for the integration environment, which really asks the user its login and password, and one always succeeding without requiring any user action.

Well, how can we define an authentication process in Play 2? A simple solution is defined with the following code: