How would one do dependency injection in scala?

Standard Java DI frameworks will usually work with Scala, but you can also use language constructs to achieve the same effect without external dependencies.


A new dependency injection library specifically for Scala is Dick Wall's SubCut.

Whereas the Jonas Bonér article referenced in Dan Story's answer emphasizes compile-time bound instances and static injection (via mix-ins), SubCut is based on runtime initialization of immutable modules, and dynamic injection by querying the bound modules by type, string names, or scala.Symbol names.

You can read more about the comparison with the Cake pattern in the GettingStarted document.


Dependency Injection itself can be done without any tool, framework or container support. You only need to remove news from your code and move them to constructors. The one tedious part that remains is wiring the objects at "the end of the world", where containers help a lot.

Though with Scala's 2.10 macros, you can generate the wiring code at compile-time and have auto-wiring and type-safety.

See the Dependency Injection in Scala Guide


A recent project illustrates a DI based purely on constructor injection: zalando/grafter

What's wrong with constructor injection again?

There are many libraries or approaches for doing dependency injection in Scala. Grafter goes back to the fundamentals of dependency injection by just using constructor injection: no reflection, no xml, no annotations, no inheritance or self-types.

Then, Grafter add to constructor injection just the necessary support to:

  • instantiate a component-based application from a configuration
  • fine-tune the wiring (create singletons)
  • test the application by replacing components
  • start / stop the application

Grafter is targeting every possible application because it focuses on associating just 3 ideas:

  • case classes and interfaces for components
  • Reader instances and shapeless for the configuration
  • tree rewriting and kiama for everything else!