Suppose we want to create an abstract Greeter component that we want to use without knowing its concrete implementation:

trait Greeter {
  def hello(name: String): Unit

A simple implementation would be:

final class PrintGreeter extends Greeter {
  override def hello(name: String) = println(s"Hello $name!") 

Let’s define some more components that depend on a Greeter:

trait Byer {
  def bye(name: String): Unit

final class PrintByer extends Byer {  
  override def bye(name: String) = println(s"Bye $name!")

final class HelloByeApp(greeter: Greeter, byer: Byer) {
  def run(): Unit = {
    println("What's your name?")
    val name = readLine()

The app above uses Greeter and Byer to hold a simple conversation with the user.

To actually run the app, we’ll have to bind the real implementations of Greeter and Byer.

import distage.{ModuleDef, Injector}

object HelloByeModule extends ModuleDef {

Since HelloByeApp is not an interface, but a final class that implements itself, we don’t have to specify an implementation class for it.

Let’s launch the app and see what happens:

val injector = Injector()

val plan = injector.plan(HelloByeModule)
val objects = injector.produceUnsafe(plan)

val app = objects.get[HelloByeApp]
// What's your name?
// kai
// Hello kai!
// Bye kai!

Given a set of bindings, such as HelloByeModule, distage will lookup the dependencies (constructor or function arguments) of each implementation and deduce a plan to satisfy each dependency using the other implementations in that module. Once finished, it will happily return the plan back to you as a simple datatype. We can print HelloByeModule’s plan while we’re at it:

// {type.Byer} ( := make[repl.Session.App0.PrintByer] ()
// {type.Greeter} ( := make[repl.Session.App0.PrintGreeter] ()
// {type.HelloByeApp} ( := make[HelloByeApp] (
//   par greeter: Greeter = lookup({type.Greeter})
//   par byer: Byer = lookup({type.Byer})
// )

Since plan is just a piece of data, we need to interpret it to create the actual object graph – Injector’s produce method is the default interpreter. Injector contains no logic of its own beyond interpreting instructions, its output is fully determined by the plan. This makes debugging quite easy.

Given that plans are data, it’s possible to verify them at compile-time or splice equivalent Scala code to do the instantiation before ever running the application. When used in that way, distage is a great alternative to compile-time frameworks such as MacWire all the while keeping the flexibility to interpret at runtime when needed. This flexibility in interpretation allows adding features, such as Plugins and Typesafe Config integration by transforming plans and bindings.

Note: classes in distage are always created exactly once, even if many different classes depend on them - they’re Singletons. Non-singleton semantics are not available, however you can create multiple named instances and disambiguate between them with @Id annotation:

import distage.Id

new ModuleDef {
  make[Byer].named("byer-2").from {
    otherByer: Byer @Id("byer-1") =>
      new Byer {
        def bye(name: String) = otherByer.bye(s"NOT-$name")
// res3: AnyRef with ModuleDef = Set(SingletonBinding({type.repl.Session.App0.Byer@byer-2},ProviderImpl(repl.Session.App0.Byer,<function1>(repl.Session.App0.Byer): repl.Session.App0.Byer),Set(<*>, <singleton>),(, SingletonBinding({type.repl.Session.App0.Byer@byer-1},TypeImpl(repl.Session.App0.PrintByer),Set(<*>, <singleton>),(

You can also create factory classes to help you mint new non-singleton instances. Auto-Factories can reduce boilerplate involved in doing this.

Modules can be combined into larger modules with ++ and overridenBy operators. Let’s use overridenBy to greet in ALL CAPS:

val caps = HelloByeModule.overridenBy(new ModuleDef {
  make[Greeter].from(new Greeter {
    override def hello(name: String) = println(s"HELLO ${name.toUpperCase}")

val capsUniverse = injector.produceUnsafe(caps)
// What's your name?
// kai
// Bye kai!

We’ve overriden the Greeter binding in HelloByeModule with an implementation of Greeter that prints in ALL CAPS. For simple cases like this we can write implementations right inside the module.

Function Bindings

To bind to a function instead of a class constructor use .from method in ModuleDef DSL:

import distage._

case class HostPort(host: String, port: Int)

class HttpServer(hostPort: HostPort)

object HttpServerModule extends ModuleDef {
  make[HttpServer].from {
    hostPort: HostPort =>
      val modifiedPort = hostPort.port + 1000
      new HttpServer(hostPort.copy(port = modifiedPort))

To inject named instances or config values, add annotations such as @Id and @ConfPath to lambda arguments’ types:

import distage.config._

object HostPortModule extends ModuleDef {
  make[HostPort].named("default").from(HostPort("localhost", 8080))
  make[HostPort].from {
    (maybeConfigHostPort: Option[HostPort] @ConfPath("http"),
     defaultHostPort: HostPort @Id("default")) =>

Given a Locator we can retrieve instances by type, call methods on them or summon them with a function:

import scala.util.Random

val objects = Injector().produceUnsafe(HelloByeModule)
// objects: Locator = com.github.pshirshov.izumi.distage.LocatorDefaultImpl@19b3aacf {
  (hello: Hello, bye: Bye) =>
    val names = Array("Snow", "Marisa", "Shelby")
    val rnd = Random.nextInt(3)
    println(s"Random index: $rnd")
// Random index: 1
// Hello Marisa
// Bye Marisa
objects.runOption { i: Int => i + 10 } match {
  case None => println("There is no Int in the object graph!")
  case Some(i) => println(s"Int is $i")
// There is no Int in the object graph!

consult ProviderMagnet docs for more details.

Set Bindings

Set bindings are useful for implementing event listeners, plugins, hooks, http routes, healthchecks, migrations, etc. Everywhere where you need to gather up a bunch of similar components is probably a good place for a Set Binding.

To define a Set binding use .many and .add methods in ModuleDef DSL.

For example, we can gather and serve all the different http4s routes added in multiple independent modules:

// boilerplate
import cats.implicits._
import cats.effect._
import distage._
import org.http4s._
import org.http4s.Uri.uri
import org.http4s.implicits._
import org.http4s.server.blaze._


implicit val contextShift = IO.contextShift(global)
implicit val timer = IO.timer(global)
object HomeRouteModule extends ModuleDef {

  val homeRoute = HttpRoutes.of[IO] { 
    case GET -> Root / "home" => Ok(s"Home page!") 


We’ve used many method to declare an open Set of http routes and then added one HTTP route into it. When module definitions are combined, Sets for the same binding will be merged together. You can summon a Set Bindings by summoning a scala Set, as in Set[HttpRoutes[IO]].

Let’s define a new module with another route:

object BlogRouteModule extends ModuleDef {

  val blogRoute = HttpRoutes.of[IO] { 
    case GET -> Root / "blog" / post => Ok(s"Blog post ``$post''!") 

Now it’s the time to define a Server component to serve all the different routes we have:

final class HttpServer(routes: Set[HttpRoutes[IO]]) {
  val router: HttpApp[IO] = 

  val serverResource = 
      .bindHttp(8080, "localhost")

object HttpServerModule extends ModuleDef {

Now, let’s wire all the modules and create the server!

val finalModule = Seq(

val objects = Injector().produceUnsafe(finalModule)

val server = objects.get[HttpServer]

Let’s check if it works: = uri("/home")))
// res9: String = "Home page!" = uri("/blog/1")))
// res10: String = "Blog post ``1''!"


consult Guice wiki on Multibindings for more details about the concept.

Injecting Implicits


Sorry, this page is not ready yet

Relevant ticket:

Implicits are managed like any other class. To make them available for summoning, declare them in a module:

import cats.Monad
import distage._
import scalaz.zio.IO
import scalaz.zio.interop.catz._

object IOMonad extends ModuleDef {
  addImplicit[Monad[IO[Throwable, ?]]]
  // same as make[Monad[IO[Throwable, ?]]].from(implicitly[Monad[IO[Throwable, ?]]])

Implicits for managed classes are injected from the object graph, NOT from the surrounding lexical scope. If they were captured from lexical scope inside ModuleDef, then classes would effectively depend on specific implementations of implicits available in scope at ModuleDef definition point. Depending on implementations is unmodular! We want to late-bind implicit dependencies same as any other dependencies, therefore you must specify implementations for implicits in ModuleDef.

import cats._
import distage._

trait KVStore[F[_]] {
  def fetch(key: String): F[String]

final class KVStoreEitherImpl(implicit F: MonadError[Either[Error, ?], Error]) extends KVStore[Either[Error, ?]] {
  def fetch(key: String) = F.raiseError(new Error(s"no value for key $key!"))

val kvstoreModuleBad = new ModuleDef {
  // We DON'T want this import to be necessary here
  // import cats.instances.either._

  make[KVStore[Either[Error, ?]]].from[KVStoreEitherImpl]

// Instead, wire implicits explicitly
val kvstoreModuleGood = new ModuleDef {

  make[KVStore[Either[Error, ?]]].from[KVStoreEitherImpl]
  // Ok to import here
  import cats.instances.either._
  // add the implicit dependency into the object graph
  addImplicit[MonadError[Either[Error, ?], Error]]

Implicits obey the usual lexical scope in user code.

You can participate in this ticket at

Resource Bindings & Lifecycle

Lifecycle is supported via Resource bindings. You can inject any cats.effect.Resource into the object graph. You can also inject DIResource classes. Global resources will be deallocated when the app or the test ends.

Note that lifecycle control via DIResource is available in non-FP applications as well via inheritance from DIResource.Simple and DIResource.Mutable.

Example with http4s Client cats Resource:

import cats.effect._
import distage._
import org.http4s.client.Client
import org.http4s.client.blaze.BlazeClientBuilder

import scala.concurrent.ExecutionContext

object App extends IOApp {
  val blazeClientModule = new ModuleDef {
    addImplicit[Bracket[IO, Throwable]]

    make[Client[IO]].fromResource { ec: ExecutionContext =>

  def run(args: List[String]): IO[ExitCode] =
    .use { // Client allocated
    }.map(_ => ExitCode.Success) // Client closed

Example with DIResource.Simple:

import distage._

class Init {
  var initialized = false

class InitResource extends DIResource.Simple[Init] {
  override def acquire = {
    val init = new Init
    init.initialized = true
  override def release(init: Init) = {
    init.initialized = false

val module = new ModuleDef {
// module: AnyRef with ModuleDef = Set(SingletonBinding({type.repl.Session.App12.Init},ResourceImpl(repl.Session.App12.Init,[A]com.github.pshirshov.izumi.fundamentals.platform.functional.Identity[A],TypeImpl(repl.Session.App12.InitResource)),Set(<*>, <singleton>),(
val closedInit = Injector().produce(module).use {
  objects =>
    val init = objects.get[Init] 
// true
// closedInit: com.github.pshirshov.izumi.fundamentals.platform.functional.package.Identity[Init] = repl.Session$App12$Init@65061c6f
// false

DIResource forms a monad and has the expected .map, .flatMap, .evalMap methods available. You can convert a DIResource into a cats.effect.Resource via .toCats method.

You need to use resource-aware Injector.produce/Injector.produceF methods to control lifecycle of the object graph.

Effect Bindings

Sometimes we need to effectfully create a component or fetch some data and inject it into the object graph during startup (e.g. read a configuration file), but the resulting component or data does not need to be closed. An example might be a global Semaphore that limit the parallelism of the entire application based on configuration value or a Dummy / test double implementation of some external service made for testing.

In these cases we can use .fromEffect to simply bind a value created effectfully.

Example with ZIO Semaphore:

import distage._
import distage.config._
import scalaz.zio._

case class Content(bytes: Array[Byte])

case class UploadConfig(maxParallelUploads: Long)

class UploaderModule extends ModuleDef {
  make[Semaphore].named("upload-limit").fromEffect {
    conf: UploadConfig @ConfPath("myapp.uploads") =>

class Uploader(limit: Semaphore @Id("upload-limit")) {
  def upload(content: Content): IO[Throwable, Unit] =

Example with a Dummy KVStore:

trait KVStore[F[_, _]] {
  def put(key: String, value: String): F[Nothing, Unit]
  def get(key: String): F[NoSuchElementException, String]

object KVStore {
  def dummy: IO[Nothing, KVStore[IO]] = for {
    ref <- Ref.make(Map.empty[String, String])
    kvStore = new KVStore[IO] {
      def put(key: String, value: String): IO[Nothing, Unit] =
        ref.update(_ + (key -> value)).void
      def get(key: String): IO[NoSuchElementException, String] = 
        for {
          map <- ref.get
          maybeValue = map.get(key)
          res <- maybeValue match {
            case None => 
            case Some(value) => 
        } yield res
  } yield kvStore

val kvStoreModule = new ModuleDef {
// kvStoreModule: AnyRef with ModuleDef = Set(SingletonBinding({type.App14.this.KVStore[scalaz.zio.IO]},EffectImpl(App14.this.KVStore[scalaz.zio.IO],[A]scalaz.zio.IO[Nothing,A],InstanceImpl(scalaz.zio.IO[Nothing,App14.this.KVStore[scalaz.zio.IO]],scalaz.zio.IO$FlatMap@41b4475e)),Set(<*>, <singleton>),(

new RTS{}.unsafeRun {
  Injector().produceF[IO[Throwable, ?]](kvStoreModule)
    .use {
      objects =>
        val kv = objects.get[KVStore[IO]]
        for {
          _ <- kv.put("apple", "pie")
          res <- kv.get("apple")
        } yield res
// res15: String = "pie"

You need to use effect-aware Injector.produceF/Injector.produceUnsafeF methods to use effect bindings.

Tagless Final Style

Tagless Final is one of the popular patterns for structuring purely-functional applications. If you’re not familiar with tagless final you can skip this section.

Brief introduction to tagless final:

Advantages of distage as a driver for TF compared to implicits:

As an example, let’s take freestyle’s tagless example and make it safer and more flexible by replacing dependencies on global imported implementations from with explicit modules.

First, the program we want to write:

import cats._
import cats.implicits._
import distage._

trait Validation[F[_]] {
  def minSize(s: String, n: Int): F[Boolean]
  def hasNumber(s: String): F[Boolean]
def Validation[F[_]: Validation]: Validation[F] = implicitly

trait Interaction[F[_]] {
  def tell(msg: String): F[Unit]
  def ask(prompt: String): F[String]
def Interaction[F[_]: Interaction]: Interaction[F] = implicitly

class TaglessProgram[F[_]: Monad: Validation: Interaction] {
  def program: F[Unit] = for {
    userInput <- Interaction[F].ask("Give me something with at least 3 chars and a number on it")
    valid     <- (Validation[F].minSize(userInput, 3), Validation[F].hasNumber(userInput)).mapN(_ && _)
    _         <- if (valid) 
                    Interaction[F].tell(s"$userInput is not valid")
  } yield ()

class Program[F[_]: TagK: Monad] extends ModuleDef {


TagK is distage’s analogue of TypeTag for higher-kinded types such as F[_], it allows preserving type-information at runtime for types that aren’t yet known at definition. You’ll need to add a TagK context bound to create a module parameterized by an abstract F[_]. Use Tag to create modules parameterized by non-higher-kinded types.


import scala.util.Try
import cats.instances.all._

def tryValidation = new Validation[Try] {
  def minSize(s: String, n: Int): Try[Boolean] = Try(s.size >= n)
  def hasNumber(s: String): Try[Boolean] = Try(s.exists(c => "0123456789".contains(c)))
def tryInteraction = new Interaction[Try] {
  def tell(s: String): Try[Unit] = Try(println(s))
  def ask(s: String): Try[String] = Try("This could have been user input 1")

object TryInterpreters extends ModuleDef {

// combine all modules
val TryProgram = new Program[Try] ++ TryInterpreters
// TryProgram: Module = Set(SingletonBinding({type.repl.Session.App16.TaglessProgram[[A]scala.util.Try[A]]},ProviderImpl(repl.Session.App16.TaglessProgram[[A]scala.util.Try[A]],<function1>(cats.Monad[[A]scala.util.Try[A]], repl.Session.App16.Validation[[A]scala.util.Try[A]], repl.Session.App16.Interaction[[A]scala.util.Try[A]]): repl.Session.App16.TaglessProgram[[A]scala.util.Try[A]]),Set(<*>, <singleton>),(, SingletonBinding({type.repl.Session.App16.Validation[scala.util.Try]},InstanceImpl(repl.Session.App16.Validation[scala.util.Try],repl.Session$App16$$anon$11@7b607b3d),Set(<*>, <singleton>),(, SingletonBinding({type.repl.Session.App16.Interaction[scala.util.Try]},InstanceImpl(repl.Session.App16.Interaction[scala.util.Try],repl.Session$App16$$anon$12@5f7ce1f),Set(<*>, <singleton>),(, SingletonBinding({type.cats.Monad[[A]scala.util.Try[A]]},InstanceImpl(cats.Monad[[A]scala.util.Try[A]],cats.instances.TryInstances$$anon$1@26924ce2),Set(<*>, <singleton>),(

// create object graph
val objects = Injector().produceUnsafe(TryProgram)
// objects: Locator = com.github.pshirshov.izumi.distage.LocatorDefaultImpl@2a8f9550

// run
// awesomesauce!
// res17: Try[Unit] = Success(())

The program module is polymorphic over its eventual monad, we can easily parameterize it with a different monad:

import cats.effect._

def SyncInterpreters[F[_]: TagK](implicit F: Sync[F]) = new ModuleDef {
  make[Validation[F]].from(new Validation[F] {
    def minSize(s: String, n: Int): F[Boolean] = F.delay(s.size >= n)
    def hasNumber(s: String): F[Boolean] = F.delay(s.exists(c => "0123456789".contains(c)))
  make[Interaction[F]].from(new Interaction[F] {
    def tell(s: String): F[Unit] = F.delay(println(s))
    def ask(s: String): F[String] = F.delay("This could have been user input 1")

def IOProgram = new Program[IO] ++ SyncInterpreters[IO]

We can leave it completely polymorphic as well:

def SyncProgram[F[_]: TagK: Sync] = new Program[F] ++ SyncInterpreters[F]

Or choose different interpreters at runtime:

def DifferentTryInterpreters = ???
def chooseInterpreters(default: Boolean) = {
  val interpreters = if (default) TryInterpreters else DifferentTryInterpreters
  new Program[Try] ++ interpreters

Modules can be polymorphic over arbitrary kinds - use TagKK to abstract over bifunctors:

class BifunctorIOModule[F[_, _]: TagKK] extends ModuleDef

Or use to abstract over any kind:

class MonadTransModule[F[_[_], _]:] extends ModuleDef
class TrifunctorModule[F[_, _, _]:] extends ModuleDef
class EldritchModule[F[+_, -_[_, _], _[_[_, _], _], _]:] extends ModuleDef

consult HKTag docs for more details.


distage-testkit module provides integration with scalatest:

libraryDependencies += Izumi.R.distage_testkit


libraryDependencies += "com.github.pshirshov.izumi.r2" %% "distage-plugins" % "0.7.0"

If you’re not using sbt-izumi-deps plugin.

Example usage:

import distage._
import com.github.pshirshov.izumi.distage.testkit.DistageSpec

class TestClass {
  def hello: String = "Hello World!"

class Test extends DistageSpec {
  override protected def makeBindings: ModuleBase = new ModuleDef {

  "TestClass" should {

    "Say hello" in di {
      testClass: TestClass =>
        assert(testClass.hello == "Hello World!")