Scaldi: Dependency injection library in scala

Table of contents
Reading Time: 2 minutes

Scaldi is the lightweight dependency injection library written in scala and it provides scala DSL for binding dependencies and injecting them.

Its depends on three concepts.

Injector – container for bindings.

Module –  where we define bindings and it extends Injector.

Injectable – trait which provide DSL for injection.

In this blog we will see how can we use it with Akka.

1. First add scaldi library dependency in your project build.sbt

2. Suppose we have an actor as below which does sum of two integer and send result back to its sender.

Below are the messages used for communication between actors.

3. Create an actor who delegate the job to this SumActor and uses scaldi library api to inject props of SumActor.

4- Now we will create a simple application using scaldi as below.

AkkaInjectable trait  provide various methods for dependency injection.

injectActorRef – creates a new actor using actorRef factory.

injectActorProps – inject props for the actor.

In class SumModule we provide binding for all actors which we want to inject as dependency in  application. In class AkkaModule we provide binding for ActorSystem.

We can combine these two module using  :: operator.

Related code can be found in github repo.  Learn more about scaldi.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading