Basics

Quick Start

Suppose we have an abstract Greeter component and some other components that depend on it:

import distage.{ModuleDef, Injector, Roots}

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

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

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()
    
    greeter.hello(name)
    byer.bye(name)
  }
}

To actually run the HelloByeApp, we have to wire implementations of Greeter and Byer into it. We will not do it directly. First we’ll only declare the component interfaces we have and the implementations we want for them:

val HelloByeModule = new ModuleDef {
  make[Greeter].from[PrintGreeter]
  make[Byer].from[PrintByer]
  make[HelloByeApp] // `.from` is not required for concrete classes 
}
// HelloByeModule: AnyRef with ModuleDef = 
// make[{type.repl.Session::repl.Session.App0::repl.Session.App0.Greeter}].from(call(Class(): repl.Session::repl.Session.App0::repl.Session.App0.PrintGreeter)) ((basics.md:66))
// make[{type.repl.Session::repl.Session.App0::repl.Session.App0.HelloByeApp}].from(call(Class(repl.Session::repl.Session.App0::repl.Session.App0.Greeter, repl.Session::repl.Session.App0::repl.Session.App0.Byer): repl.Session::repl.Session.App0::repl.Session.App0.HelloByeApp)) ((basics.md:68))
// make[{type.repl.Session::repl.Session.App0::repl.Session.App0.Byer}].from(call(Class(): repl.Session::repl.Session.App0::repl.Session.App0.PrintByer)) ((basics.md:67))

ModuleDef merely contains a description of the desired object graph, let’s transform that high-level description into an actionable series of steps - an OrderedPlan, a datatype we can inspect, test or verify at compile-time – without actually creating any objects or executing any effects.

val plan = Injector().plan(HelloByeModule, Roots.Everything)
// plan: izumi.distage.model.plan.OrderedPlan = 
// {type.Activation} (InjectorDefaultImpl.scala:67) := value izumi.distage.model.definition.Activation#-1609326920
// {type.Session::App0::Byer} (basics.md:67) := call(Class(): Session::App0::PrintByer) {}
// {type.InjectorFactory} (InjectorDefaultImpl.scala:65) := value distage.Injector$#377809143
// {type.Session::App0::Greeter} (basics.md:66) := call(Class(): Session::App0::PrintGreeter) {}
// {type.BootstrapModule} (InjectorDefaultImpl.scala:66) := value izumi.distage.model.definition.BootstrapModule$$anon$1#1678334217
// {type.PlannerInput} (InjectorDefaultImpl.scala:64) := value izumi.distage.model.PlannerInput#-1168175418
// {type.Session::App0::HelloByeApp} (basics.md:68) := call(Class(Session::App0::Greeter, Session::App0::Byer): Session::App0::HelloByeApp) {
//   arg greeter: Session::App0::Greeter = lookup({type.Session::App0::Greeter})
//   arg byer: Session::App0::Byer = lookup({type.Session::App0::Byer})
// }
// {type.Bootloader} (InjectorDefaultImpl.scala:68) := call(Class(BootstrapModule, Activation, PlannerInput, InjectorFactory): Bootloader) {
//   arg bootstrapModule: BootstrapModule = lookup({type.BootstrapModule})
//   arg activation: Activation = lookup({type.Activation})
//   arg input: PlannerInput = lookup({type.PlannerInput})
//   arg injectorFactory: InjectorFactory = lookup({type.InjectorFactory})
// }

The series of steps must be executed to produce the object graph. Injector.produce will interpret the steps into a Resource value, that holds the lifecycle of the object graph:

// Interpret into DIResource

val resource = Injector().produce(plan)
// resource: izumi.distage.model.definition.DIResource.DIResourceBase[izumi.fundamentals.platform.functional.package.Identity, izumi.distage.model.Locator] = izumi.distage.model.definition.DIResource$$anon$11@31e7815d

// Use the object graph:
// After `.use` exits, all objects will be deallocated,
// and all allocated resources will be freed.

resource.use {
  objects =>
    objects.get[HelloByeApp].run()
}
// What's your name?
// > izumi
// Hello izumi!
// Bye izumi!
// res1: izumi.fundamentals.platform.functional.package.Identity[Unit] = ()

distage always creates components exactly once, even if multiple other objects depend on them. There is only a “Singleton” scope. It’s impossible to create non-singletons in distage. If you need multiple singleton instances of the same type, you can create named instances and disambiguate between them using @Id annotation.

import distage.Id

new ModuleDef {
  make[Byer].named("byer-1").from[PrintByer]
  make[Byer].named("byer-2").from {
    otherByer: Byer @Id("byer-1") =>
      new Byer {
        def bye(name: String) = otherByer.bye(s"NOT-$name")
      }
  }
}
// res2: AnyRef with ModuleDef = 
// make[{type.repl.Session::repl.Session.App0::repl.Session.App0.Byer@byer-2}].from(call(<function1>(repl.Session::repl.Session.App0::repl.Session.App0.Byer): repl.Session::repl.Session.App0::repl.Session.App0.Byer)) ((basics.md:98))
// make[{type.repl.Session::repl.Session.App0::repl.Session.App0.Byer@byer-1}].from(call(Class(): repl.Session::repl.Session.App0::repl.Session.App0.PrintByer)) ((basics.md:97))

You can abstract over annotations using type aliases or string constants:

object Ids {
  final val byer1Id = "byer-1"
  type Byer1 = Byer @Id(byer1Id)
}

To create non-singleton components you must use explicit factory classes. You can use Auto-Factories implementations for these factories.

Activation Axis

You can choose between different implementations of a component using Axis tags:

import distage.{Axis, Activation, ModuleDef, Injector, Roots}

class AllCapsGreeter extends Greeter {
  def hello(name: String) = println(s"HELLO ${name.toUpperCase}")
}

// declare the configuration axis for our components

object Style extends Axis {
  case object AllCaps extends AxisValueDef
  case object Normal extends AxisValueDef
}

// Declare a module with several implementations of Greeter
// but in different environments

val TwoImplsModule = new ModuleDef {
  make[Greeter].tagged(Style.Normal)
    .from[PrintGreeter]
  
  make[Greeter].tagged(Style.AllCaps)
    .from[AllCapsGreeter]
}
// TwoImplsModule: AnyRef with ModuleDef = 
// make[{type.repl.Session::repl.Session.App0::repl.Session.App0.Greeter}].from(call(Class(): repl.Session::repl.Session.App0::repl.Session.App0.PrintGreeter)).tagged(Set(AxisTag(style:normal))) ((basics.md:134))
// make[{type.repl.Session::repl.Session.App0::repl.Session.App0.Greeter}].from(call(Class(): repl.Session::repl.Session.App0::repl.Session.App0.AllCapsGreeter)).tagged(Set(AxisTag(style:allcaps))) ((basics.md:137))

// Combine previous `HelloByeModule` with our new module
// While overriding `make[Greeter]` bindings from the first module 

val CombinedModule = HelloByeModule overridenBy TwoImplsModule
// CombinedModule: izumi.distage.model.definition.Module = 
// make[{type.repl.Session::repl.Session.App0::repl.Session.App0.Greeter}].from(call(Class(): repl.Session::repl.Session.App0::repl.Session.App0.PrintGreeter)).tagged(Set(AxisTag(style:normal))) ((basics.md:134))
// make[{type.repl.Session::repl.Session.App0::repl.Session.App0.Greeter}].from(call(Class(): repl.Session::repl.Session.App0::repl.Session.App0.AllCapsGreeter)).tagged(Set(AxisTag(style:allcaps))) ((basics.md:137))
// make[{type.repl.Session::repl.Session.App0::repl.Session.App0.HelloByeApp}].from(call(Class(repl.Session::repl.Session.App0::repl.Session.App0.Greeter, repl.Session::repl.Session.App0::repl.Session.App0.Byer): repl.Session::repl.Session.App0::repl.Session.App0.HelloByeApp)) ((basics.md:68))
// make[{type.repl.Session::repl.Session.App0::repl.Session.App0.Byer}].from(call(Class(): repl.Session::repl.Session.App0::repl.Session.App0.PrintByer)) ((basics.md:67))

// Choose component configuration when making an Injector:

val capsInjector = Injector(Activation(Style -> Style.AllCaps))
// capsInjector: Injector = izumi.distage.InjectorDefaultImpl@6ff8dd1

// Check the result:

capsInjector
  .produceGet[HelloByeApp](CombinedModule)
  .use(_.run())
// What's your name?
// > kai
// HELLO KAI
// Bye kai!
// res3: izumi.fundamentals.platform.functional.package.Identity[Unit] = ()

// Check that result changes with a different configuration:

Injector(Activation(Style -> Style.Normal))
  .produceGet[HelloByeApp](CombinedModule)
  .use(_.run())
// What's your name?
// > Pavel
// Hello Pavel!
// Bye Pavel!
// res4: izumi.fundamentals.platform.functional.package.Identity[Unit] = ()

distage.StandardAxis contains bundled Axes for back-end development: Repo.Prod/Dummy, Env.Prod/Test & ExternalApi.Prod/Mock

In distage-framework’s RoleAppLauncher, you can choose axes using the -u command-line parameter:

./launcher -u repo:dummy -u env:prod app1

In distage-testkit, specify axes via TestConfig:

import distage.StandardAxis.Repo
import izumi.distage.testkit.TestConfig
import izumi.distage.testkit.scalatest.DistageBIOSpecScalatest

class AxisTest extends DistageBIOSpecScalatest[zio.IO] {
  override protected def config: TestConfig = super.config.copy(
    // choose implementations tagged `Repo.Dummy` when multiple implementations with `Repo.*` tags are available
    activation = Activation(Repo -> Repo.Dummy)
  )
}

Multi-dimensionality

There may be many configuration axes in an application and components can specify multiple axis choices at once:

import distage.StandardAxis.Env

class TestPrintGreeter extends Greeter {
  def hello(name: String) = println(s"Test 1 2, hello $name")
}

// declare 3 possible implementations

val TestModule = new ModuleDef {
  make[Greeter].tagged(Style.Normal, Env.Prod).from[PrintGreeter]
  make[Greeter].tagged(Style.Normal, Env.Test).from[TestPrintGreeter]
  make[Greeter].tagged(Style.AllCaps).from[AllCapsGreeter]
}
// TestModule: AnyRef with ModuleDef = 
// make[{type.repl.Session::repl.Session.App0::repl.Session.App0.Greeter}].from(call(Class(): repl.Session::repl.Session.App0::repl.Session.App0.PrintGreeter)).tagged(Set(AxisTag(style:normal), AxisTag(env:prod))) ((basics.md:190))
// make[{type.repl.Session::repl.Session.App0::repl.Session.App0.Greeter}].from(call(Class(): repl.Session::repl.Session.App0::repl.Session.App0.TestPrintGreeter)).tagged(Set(AxisTag(style:normal), AxisTag(env:test))) ((basics.md:191))
// make[{type.repl.Session::repl.Session.App0::repl.Session.App0.Greeter}].from(call(Class(): repl.Session::repl.Session.App0::repl.Session.App0.AllCapsGreeter)).tagged(Set(AxisTag(style:allcaps))) ((basics.md:192))

def runWith(activation: Activation) =
  Injector(activation).produceRun(TestModule) {
    greeter: Greeter => greeter.hello("$USERNAME")
  }

// Production Normal Greeter

runWith(Activation(Style -> Style.Normal, Env -> Env.Prod))
// Hello $USERNAME!

// Test Normal Greeter

runWith(Activation(Style -> Style.Normal, Env -> Env.Test))
// Test 1 2, hello $USERNAME

// Both Production and Test Caps Greeters are the same:

runWith(Activation(Style -> Style.AllCaps, Env -> Env.Prod))
// HELLO $USERNAME

runWith(Activation(Style -> Style.AllCaps, Env -> Env.Test))
// HELLO $USERNAME

Resource Bindings, Lifecycle

You can specify object lifecycle by injecting cats.effect.Resource, zio.ZManaged or distage.DIResource values that specify the allocation and finalization actions for an object.

Injector itself only returns a DIResource value that can be used to create and finalize the object graph, this value is pure and can be reused multiple times. A DIResource is consumed using its .use method, the function passed to use will receive an allocated resource and when the function exits the resource will be deallocated.

Example with cats.effect.Resource:

import distage.{Roots, ModuleDef, Injector}
import cats.effect.{Bracket, Resource, IO}

class DBConnection
class MessageQueueConnection

val dbResource = Resource.make(
  acquire = IO { 
    println("Connecting to DB!")
    new DBConnection 
})(release = _ => IO(println("Disconnecting DB")))
// dbResource: Resource[IO, DBConnection] = Allocate(<function1>)

val mqResource = Resource.make(
  acquire = IO {
   println("Connecting to Message Queue!")
   new MessageQueueConnection 
})(release = _ => IO(println("Disconnecting Message Queue")))
// mqResource: Resource[IO, MessageQueueConnection] = Allocate(<function1>)

class MyApp(db: DBConnection, mq: MessageQueueConnection) {
  val run = IO(println("Hello World!"))
}

val module = new ModuleDef {
  make[DBConnection].fromResource(dbResource)
  make[MessageQueueConnection].fromResource(mqResource)
  addImplicit[Bracket[IO, Throwable]]
  make[MyApp]
}
// module: AnyRef with ModuleDef = 
// make[{type.cats.effect.Bracket[=λ %1:0 → IO[+1:0],=Throwable]}].from(value(cats.effect.IOLowPriorityInstances$IOEffect@6a1b82aa: cats.effect.Bracket[=λ %1:0 → IO[+1:0],=Throwable])) ((basics.md:254))
// make[{type.repl.Session::repl.Session.App9::repl.Session.App9.MessageQueueConnection}].from(allocate[λ %0 → cats.effect.IO[+0]](call(izumi.distage.model.reflection.Provider$ProviderImpl$$Lambda$17861/0x00000008441f8040@272561cf(cats.effect.Bracket[=λ %0 → IO[+0],=Throwable]): izumi.distage.model.definition.DIResource::izumi.distage.model.definition.DIResource.FromCats[=λ %1:0 → IO[+1:0],=Session::App9::MessageQueueConnection]))) ((basics.md:253))
// make[{type.repl.Session::repl.Session.App9::repl.Session.App9.DBConnection}].from(allocate[λ %0 → cats.effect.IO[+0]](call(izumi.distage.model.reflection.Provider$ProviderImpl$$Lambda$17861/0x00000008441f8040@4985c766(cats.effect.Bracket[=λ %0 → IO[+0],=Throwable]): izumi.distage.model.definition.DIResource::izumi.distage.model.definition.DIResource.FromCats[=λ %1:0 → IO[+1:0],=Session::App9::DBConnection]))) ((basics.md:252))
// make[{type.repl.Session::repl.Session.App9::repl.Session.App9.MyApp}].from(call(Class(repl.Session::repl.Session.App9::repl.Session.App9.DBConnection, repl.Session::repl.Session.App9::repl.Session.App9.MessageQueueConnection): repl.Session::repl.Session.App9::repl.Session.App9.MyApp)) ((basics.md:255))

Will produce the following output:

import distage.DIKey

val objectGraphResource = Injector().produceF[IO](module, Roots(root = DIKey[MyApp]))
// objectGraphResource: izumi.distage.model.definition.DIResource.DIResourceBase[IO, izumi.distage.model.Locator] = izumi.distage.model.definition.DIResource$$anon$11@7df90113

objectGraphResource
  .use(_.get[MyApp].run)
  .unsafeRunSync()
// Connecting to DB!
// Connecting to Message Queue!
// Hello World!
// Disconnecting Message Queue
// Disconnecting DB

Lifecycle management with DIResource is also available without an effect type, via DIResource.Simple and DIResource.Mutable:

import distage.{DIResource, Roots, ModuleDef, Injector}

class Init {
  var initialized = false
}

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

val module = new ModuleDef {
  make[Init].fromResource[InitResource]
}
// module: AnyRef with ModuleDef = 
// make[{type.repl.Session::repl.Session.App11::repl.Session.App11.Init}].from(allocate[λ %0 → 0](call(Class(): repl.Session::repl.Session.App11::repl.Session.App11.InitResource))) ((basics.md:300))

val closedInit = Injector()
  .produceGet[Init](module)
  .use {
    init =>
      println(init.initialized)
      init
}
// true
// closedInit: izumi.fundamentals.platform.functional.package.Identity[Init] = repl.Session$App11$Init@24c0f244

println(closedInit.initialized)
// false

DIResource forms a monad and has the expected .map, .flatMap, .evalMap, .mapK methods.

You can convert between DIResource and cats.effect.Resource via .toCats/.fromCats methods, and between zio.ZManaged via .toZIO/.fromZIO.

Set Bindings

Set bindings are useful for implementing listeners, plugins, hooks, http routes, healthchecks, migrations, etc. Everywhere where a collection of components is required, a Set Binding is appropriate.

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

For example, we may declare many http4s routes and serve them all from a central router:

import cats.implicits._
import cats.effect.{Bracket, IO, Resource}
import distage.{Roots, ModuleDef, Injector}
import org.http4s._
import org.http4s.server.Server
import org.http4s.client.Client
import org.http4s.dsl.io._
import org.http4s.implicits._
import org.http4s.server.blaze.BlazeServerBuilder
import org.http4s.client.blaze.BlazeClientBuilder

import scala.concurrent.ExecutionContext.Implicits.global

implicit val contextShift = IO.contextShift(global)
implicit val timer = IO.timer(global)
val homeRoute = HttpRoutes.of[IO] { 
  case GET -> Root / "home" => Ok(s"Home page!") 
}
// homeRoute: HttpRoutes[IO] = Kleisli(org.http4s.HttpRoutes$$$Lambda$17901/0x000000084421b040@247da74a)

object HomeRouteModule extends ModuleDef {
  many[HttpRoutes[IO]]
    .add(homeRoute)
}

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:

val blogRoute = HttpRoutes.of[IO] { 
  case GET -> Root / "blog" / post => Ok(s"Blog post ``$post''!") 
}
// blogRoute: HttpRoutes[IO] = Kleisli(org.http4s.HttpRoutes$$$Lambda$17901/0x000000084421b040@909916e)

object BlogRouteModule extends ModuleDef {  
  many[HttpRoutes[IO]]
    .add(blogRoute)
}

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

def makeHttp4sServer(routes: Set[HttpRoutes[IO]]): Resource[IO, Server[IO]] = {
  // create a top-level router by combining all the routes
  val router: HttpApp[IO] = routes.toList.foldK.orNotFound

  // return a Resource value that will setup an http4s server 
  BlazeServerBuilder[IO]
    .bindHttp(8080, "localhost")
    .withHttpApp(router)
    .resource
}

object HttpServerModule extends ModuleDef {
  make[Server[IO]].fromResource(makeHttp4sServer _)
  make[Client[IO]].fromResource(BlazeClientBuilder[IO](global).resource)
  addImplicit[Bracket[IO, Throwable]] // required for cats `Resource` in `fromResource`
}

// join all the module definitions
def finalModule = Seq(
  HomeRouteModule,
  BlogRouteModule,
  HttpServerModule,
).merge

// wire the graph
val objects = Injector().produceF[IO](finalModule, Roots.Everything).unsafeGet().unsafeRunSync()
// objects: izumi.distage.model.Locator = izumi.distage.LocatorDefaultImpl@3c7f2bc9

val server = objects.get[Server[IO]]
// server: Server[IO] = BlazeServer(/127.0.0.1:8080)
val client = objects.get[Client[IO]]
// client: Client[IO] = org.http4s.client.Client$$anon$1@1f0ebcd0

Check if it works:

// check home page
client.expect[String]("http://localhost:8080/home").unsafeRunSync()
// res14: String = Home page!

// check blog page
client.expect[String]("http://localhost:8080/blog/1").unsafeRunSync()
// res15: String = Blog post ``1''!

Further reading: the same concept is called Multibindings in Guice.

Effect Bindings

Sometimes we want to effectfully create a component, but the resulting component or data does not need to be deallocated. An example might be a global Semaphore to limit the parallelism of the entire application based on configuration, or a test implementation of some service made with Refs.

In these cases we can use .fromEffect to create a value using an effectful constructor.

Example with a Ref-based Tagless Final KVStore:

import distage.{Roots, ModuleDef, Injector}
import izumi.functional.bio.{BIOMonadError, BIOPrimitives, F}
import zio.{Task, IO}

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

def dummyKVStore[F[+_, +_]: BIOMonadError: BIOPrimitives]: F[Nothing, KVStore[F]] = {
  for {
    ref <- F.mkRef(Map.empty[String, String])
  } yield new KVStore[F] {
    def put(key: String, value: String): F[Nothing, Unit] = {
      ref.update_(_ + (key -> value))
    }
  
    def get(key: String): F[NoSuchElementException, String] = {
      for {
        map <- ref.get
        res <- map.get(key) match {
          case Some(value) => F.pure(value)
          case None        => F.fail(new NoSuchElementException(key))
        }
      } yield res
    }
  }
}

def kvStoreModule = new ModuleDef {
  make[KVStore[IO]].fromEffect(dummyKVStore[IO])
}

val io = Injector()
  .produceRunF[Task, String](kvStoreModule) {
    kv: KVStore[IO] =>
      for {
        _    <- kv.put("apple", "pie")
        res1 <- kv.get("apple")
        _    <- kv.put("apple", "ipad")
        res2 <- kv.get("apple")
      } yield res1 + res2
  }
// io: Task[String] = zio.ZIO$CheckInterrupt@134776d3

zio.Runtime.default.unsafeRun(io)
// res18: String = pieipad

You need to use effect-aware Injector.produceF method to use effect bindings.

ZIO Has Bindings

You can inject into ZIO Environment using make[_].fromHas syntax for ZLayer, ZManaged, ZIO or any F[_, _, _]: BIOLocal:

import zio._
import distage._

def zioEnvCtor: URIO[Has[Dep1] with Has[Dep2], X] = ZIO.succeed(X)
def zmanagedEnvCtor: URManaged[Has[Dep1] with Has[Dep2], X] = ZManaged.succeed(X)
def zlayerEnvCtor: URLayer[Has[Dep1] with Has[Dep2], Has[X]] = ZLayer.succeed(X)

def module1 = new ModuleDef {
  make[X].fromHas(zioEnvCtor)
  // or
  make[X].fromHas(zmanagedEnvCtor)
  // or
  make[X].fromHas(zlayerEnvCtor)
}

You can also mix environment and parameter dependencies at the same time in one constructor:

def zioArgEnvCtor(a: Arg1, b: Arg2): URLayer[Has[Dep1], Has[X]] = ZLayer.fromService(dep1 => X(a, b, dep1))

def module2 = new ModuleDef {
  make[X].fromHas(zioArgEnvCtor _)
}

zio.Has implementations are derived at compile-time by HasConstructor macro and can be summoned at need.

Example:

import distage.{DIKey, ModuleDef, Injector, ProviderMagnet, Tag}
import izumi.distage.constructors.TraitConstructor
import zio.console.{putStrLn, Console}
import zio.{UIO, URIO, ZIO, Ref, Task, Has}

trait Hello {
  def hello: UIO[String]
}
trait World {
  def world: UIO[String]
}

// Environment forwarders that allow
// using service functions from everywhere

val hello: URIO[Has[Hello], String] = ZIO.accessM(_.get.hello)
// hello: URIO[Has[Hello], String] = zio.ZIO$Read@42d2fe32

val world: URIO[Has[World], String] = ZIO.accessM(_.get.world)
// world: URIO[Has[World], String] = zio.ZIO$Read@5ef7a44a

// service implementations

val makeHello = {
  (for {
    _     <- putStrLn("Creating Enterprise Hellower...")
    hello = new Hello { val hello = UIO("Hello") }
  } yield hello).toManaged { _ =>
    putStrLn("Shutting down Enterprise Hellower")
  }
}
// makeHello: zio.ZManaged[Console, Nothing, AnyRef with Hello{val hello: zio.UIO[String]}] = zio.ZManaged@558c683c

val makeWorld = {
  for {
    counter <- Ref.make(0)
  } yield new World {
    val world = counter.get.map(c => if (c < 1) "World" else "THE World")
  }
}
// makeWorld: ZIO[Any, Nothing, AnyRef with World{val world: zio.ZIO[Any,Nothing,String]}] = zio.ZIO$FlatMap@20361edc

// the main function

val turboFunctionalHelloWorld: URIO[Has[Hello] with Has[World] with Has[Console.Service], Unit] = {
  for {
    hello <- hello
    world <- world
    _     <- putStrLn(s"$hello $world")
  } yield ()
}
// turboFunctionalHelloWorld: URIO[Has[Hello] with Has[World] with Has[Console.Service], Unit] = zio.ZIO$FlatMap@18443c3d

def module = new ModuleDef {
  make[Hello].fromHas(makeHello)
  make[World].fromHas(makeWorld)
  make[Console.Service].fromHas(Console.live)
  make[Unit].fromHas(turboFunctionalHelloWorld)
}

val main = Injector()
  .produceRunF[Task, Unit](module)((_: Unit) => Task.unit)
// main: Task[Unit] = zio.ZIO$CheckInterrupt@79bce3ab

zio.Runtime.default.unsafeRun(main)
// Creating Enterprise Hellower...
// Hello World
// Shutting down Enterprise Hellower

Converting between ZIO environment dependencies and parameters

Any ZIO Service that requires an environment can be turned into a service without an environment dependency by providing the dependency in each method. This pattern can be generalized by implementing an instance of cats.Contravariant (or cats.tagless.FunctorK) for your services and using it to turn environment dependencies into constructor parameters – that way ZIO Environment can be used uniformly for declaration of dependencies, but the dependencies used inside the service do not leak to other services calling it. Details: https://gitter.im/ZIO/Core?at=5dbb06a86570b076740f6db2

Example:

import cats.Contravariant
import distage.{Roots, Injector, ModuleDef, ProviderMagnet, Tag, TagK, HasConstructor}
import zio.{Task, UIO, URIO, ZIO, Has}

trait Dependee[-R] {
  def x(y: String): URIO[R, Int]
}
trait Depender[-R] {
  def y: URIO[R, String]
}
implicit val contra1: Contravariant[Dependee] = new Contravariant[Dependee] {
  def contramap[A, B](fa: Dependee[A])(f: B => A): Dependee[B] = new Dependee[B] { def x(y: String) = fa.x(y).provideSome(f) }
}
// contra1: Contravariant[Dependee] = repl.Session$App22$$anon$15@31e55dfd
implicit val contra2: Contravariant[Depender] = new Contravariant[Depender] {
  def contramap[A, B](fa: Depender[A])(f: B => A): Depender[B] = new Depender[B] { def y = fa.y.provideSome(f) }
}
// contra2: Contravariant[Depender] = repl.Session$App22$$anon$17@8792a28

type DependeeR = Has[Dependee[Any]]
type DependerR = Has[Depender[Any]]
object dependee extends Dependee[DependeeR] { def x(y: String) = ZIO.accessM(_.get.x(y)) }
object depender extends Depender[DependerR] { def y            = ZIO.accessM(_.get.y) }

// cycle
object dependerImpl extends Depender[DependeeR] {
  def y: URIO[DependeeR, String] = dependee.x("hello").map(_.toString)
}
object dependeeImpl extends Dependee[DependerR] {
  def x(y: String): URIO[DependerR, Int] = {
    if (y == "hello") UIO(5) 
    else depender.y.map(y.length + _.length)
  }
}

/** Fulfill the environment dependencies of a service from the object graph */
def fullfill[R: Tag: HasConstructor, M[_]: TagK: Contravariant](service: M[R]): ProviderMagnet[M[Any]] = {
  HasConstructor[R]
    .map(depsCakeR => Contravariant[M].contramap(service)(_ => depsCakeR))
}

def module = new ModuleDef {
  make[Depender[Any]].from(fullfill(dependerImpl))
  make[Dependee[Any]].from(fullfill(dependeeImpl))
}

Injector()
  .produceRunF(module) {
    HasConstructor[DependeeR].map {
      (for {
        r <- dependee.x("zxc")
        _ <- Task(println(s"result: $r"))
      } yield ()).provide(_)
    }
  }.fold(_ => 1, _ => 0)
// res23: URIO[Any, Int] = <function1>

Auto-Traits

distage can instantiate traits and structural types. All unimplemented fields in a trait or a refinement are filled in from the object graph.

Trait implementations are derived at compile-time by TraitConstructor macro and can be summoned at need.

If a suitable trait is specified as an implementation class for a binding, TraitConstructor will be used automatically:

Example:

import distage.{ModuleDef, Id, Injector}

trait Trait1 {
  def a: Int @Id("a")
}
trait Trait2 {
  def b: Int @Id("b")
}

/** All methods in this trait are implemented,
  * so a constructor for it will be generated
  * even though it's not a class */
trait Pluser {
  def plus(a: Int, b: Int) = a + b
}

trait PlusedInt {
  def result(): Int
}
object PlusedInt {

  /**
    * Besides the dependency on `Pluser`,
    * this class defines 2 more dependencies
    * to be injected from the object graph:
    *
    * `def a: Int @Id("a")` and
    * `def b: Int @Id("b")`
    * 
    * When an abstract type is declared as an implementation,
    * its no-argument abstract defs & vals are considered as
    * dependency parameters by TraitConstructor. (empty-parens and
    * parameterized methods are not considered parameters)
    *
    * Here, using an abstract class directly as an implementation
    * lets us avoid writing a lengthier constructor, like this one:
    * 
    * {{{
    *   final class Impl(
    *     pluser: Pluser,
    *     override val a: Int @Id("a"),
    *     override val b: Int @Id("b"),
    *   ) extends PlusedInt with Trait1 with Trait2
    * }}}
    */
  abstract class Impl(
    pluser: Pluser
  ) extends PlusedInt
    with Trait1
    with Trait2 {
    override def result(): Int = {
      pluser.plus(a, b)
    }
  }

}

Injector()
  .produceRun(new ModuleDef {
    make[Int].named("a").from(1)
    make[Int].named("b").from(2)
    make[Pluser]
    make[PlusedInt].from[PlusedInt.Impl]
  }) {
    plusedInt: PlusedInt => 
      plusedInt.result
  }
// res25: Int = 3

Abstract classes or traits without obvious concrete subclasses may hinder the readability of a codebase, if you still want to use them to avoid writing the full constructor, you may use an optional @impl documenting annotation to aid the reader in understanding your intention.

import distage.impl

@impl abstract class Impl(
  pluser: Pluser
) extends PlusedInt

Auto-Factories

distage can instantiate ‘factory’ classes from suitable traits. This feature is especially useful with Akka. All unimplemented methods with parameters in a trait will be filled by factory methods:

Given a class ActorFactory:

import distage.ModuleDef
import java.util.UUID

class SessionStorage

class UserActor(sessionId: UUID, sessionStorage: SessionStorage)

trait ActorFactory {
  // UserActor will be created as follows:
  //   sessionId argument is provided by the user
  //   sessionStorage argument is wired from the object graph
  def createActor(sessionId: UUID): UserActor
}

And a binding of ActorFactory without an implementation

class ActorModule extends ModuleDef {
  make[ActorFactory]
}

distage will derive and bind the following implementation for ActorFactory:

class ActorFactoryImpl(sessionStorage: SessionStorage) extends ActorFactory {
  override def createActor(sessionId: UUID): UserActor = {
    new UserActor(sessionId, sessionStorage)
  }
}

@With annotation can be used to specify the implementation class, to avoid leaking the implementation type in factory method result:

import distage.{ModuleDef, Injector, With}

trait Actor { 
  def receive(msg: Any): Unit
}

object Actor {
  trait Factory {
    def newActor(id: String): Actor @With[Actor.Impl]
  }

  final class Impl(id: String, config: Actor.Configuration) extends Actor {
    def receive(msg: Any) = {
      val response = s"Actor `$id` received a message: $msg"
      println(if (config.allCaps) response.toUpperCase else response)
    }
  }

  final case class Configuration(allCaps: Boolean)
}

val factoryModule = new ModuleDef {
  make[Actor.Factory]
  make[Actor.Configuration].from(Actor.Configuration(allCaps = false))
}
// factoryModule: AnyRef with ModuleDef = 
// make[{type.repl.Session::repl.Session.App26::repl.Session.App26.Actor::repl.Session.App26.Actor.Configuration}].from(call(izumi.distage.model.providers.ProviderMagnet$$$Lambda$17180/0x00000008427ff840@304438fb(): repl.Session::repl.Session.App26::repl.Session.App26.Actor::repl.Session.App26.Actor.Configuration)) ((basics.md:892))
// make[{type.repl.Session::repl.Session.App26::repl.Session.App26.Actor::repl.Session.App26.Actor.Factory}].from(call(Factory(repl.Session::repl.Session.App26::repl.Session.App26.Actor::repl.Session.App26.Actor.Configuration): repl.Session::repl.Session.App26::repl.Session.App26.Actor::repl.Session.App26.Actor.Factory)) ((basics.md:891))

Injector()
  .produceGet[Actor.Factory](factoryModule)
  .use(_.newActor("Martin Odersky").receive("ping"))
// Actor `Martin Odersky` received a message: ping
// res27: izumi.fundamentals.platform.functional.package.Identity[Unit] = ()

You can use this feature to concisely provide non-Singleton semantics for some of your components.

Factory implementations are derived at compile-time by FactoryConstructor macro and can be summoned at need.

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:

For 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.Monad
import cats.effect.{Sync, IO}
import cats.syntax.all._
import distage.{Roots, Module, ModuleDef, Injector, Tag, TagK, TagKK}

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("awesomesauce!")
                 else       Interaction[F].tell(s"$userInput is not valid")
  } yield ()
}

def ProgramModule[F[_]: TagK: Monad] = new ModuleDef {
  make[TaglessProgram[F]]
  addImplicit[Monad[F]]
}

TagK is distage’s analogue of TypeTag for higher-kinded types such as F[_], it allows preserving type-information at runtime for type parameters. You’ll need to add a TagK context bound to create a module parameterized by an abstract F[_]. To parameterize by non-higher-kinded types, use just Tag.

Now the interpreters for Validation and Interaction:

final class SyncValidation[F[_]](implicit F: Sync[F]) extends 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)))
}
  
final class SyncInteraction[F[_]](implicit F: Sync[F]) extends 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 SyncInterpreters[F[_]: TagK: Sync] = {
  new ModuleDef {
    make[Validation[F]].from[SyncValidation[F]]
    make[Interaction[F]].from[SyncInteraction[F]]
    addImplicit[Sync[F]]
  }
}

// combine all modules

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

// create object graph Resource

val objectsResource = Injector().produceF[IO](SyncProgram[IO], Roots.Everything)
// objectsResource: izumi.distage.model.definition.DIResource.DIResourceBase[IO, izumi.distage.model.Locator] = izumi.distage.model.definition.DIResource$$anon$11@4359501

// run

objectsResource.use(_.get[TaglessProgram[IO]].program).unsafeRunSync()
// awesomesauce!

The program module is polymorphic over effect type. It can be instantiated by a different effect:

import zio.interop.catz._
import zio.Task

val ZIOProgram = ProgramModule[Task] ++ SyncInterpreters[Task]
// ZIOProgram: Module = 
// make[{type.cats.effect.Sync[=λ %0 → ZIO[-Any,+Throwable,+0]]}].from(value(zio.interop.CatsConcurrent@3290d922: cats.effect.Sync[=λ %0 → ZIO[-Any,+Throwable,+0]])) ((basics.md:972))
// make[{type.cats.Monad[=λ %0 → ZIO[-Any,+Throwable,+0]]}].from(value(zio.interop.CatsConcurrent@3290d922: cats.Monad[=λ %0 → ZIO[-Any,+Throwable,+0]])) ((basics.md:949))
// make[{type.repl.Session::repl.Session.App28::repl.Session.App28.Validation[=λ %0 → ZIO[-Any,+Throwable,+0]]}].from(call(Class(cats.effect.Sync[=λ %0 → ZIO[-Any,+Throwable,+0]]): repl.Session::repl.Session.App28::repl.Session.App28.SyncValidation[=λ %0 → ZIO[-Any,+Throwable,+0]])) ((basics.md:970))
// make[{type.repl.Session::repl.Session.App28::repl.Session.App28.TaglessProgram[=λ %0 → ZIO[-Any,+Throwable,+0]]}].from(call(Class(cats.Monad[=λ %0 → ZIO[-Any,+Throwable,+0]], repl.Session::repl.Session.App28::repl.Session.App28.Validation[=λ %0 → ZIO[-Any,+Throwable,+0]], repl.Session::repl.Session.App28::repl.Session.App28.Interaction[=λ %0 → ZIO[-Any,+Throwable,+0]]): repl.Session::repl.Session.App28::repl.Session.App28.TaglessProgram[=λ %0 → ZIO[-Any,+Throwable,+0]])) ((basics.md:948))
// make[{type.repl.Session::repl.Session.App28::repl.Session.App28.Interaction[=λ %0 → ZIO[-Any,+Throwable,+0]]}].from(call(Class(cats.effect.Sync[=λ %0 → ZIO[-Any,+Throwable,+0]]): repl.Session::repl.Session.App28::repl.Session.App28.SyncInteraction[=λ %0 → ZIO[-Any,+Throwable,+0]])) ((basics.md:971))

We may even choose different interpreters at runtime:

import zio.RIO
import zio.console.{Console, getStrLn, putStrLn}

object RealInteractionZIO extends Interaction[RIO[Console, ?]] {
  def tell(s: String): RIO[Console, Unit]  = putStrLn(s)
  def ask(s: String): RIO[Console, String] = putStrLn(s) *> getStrLn
}

val RealInterpretersZIO = {
  SyncInterpreters[RIO[Console, ?]] overridenBy new ModuleDef {
    make[Interaction[RIO[Console, ?]]].from(RealInteractionZIO)
  }
}
// RealInterpretersZIO: Module = 
// make[{type.repl.Session::repl.Session.App28::repl.Session.App28.Validation[=λ %0 → ZIO[-Has[=package::Console::Service],+Throwable,+0]]}].from(call(Class(cats.effect.Sync[=λ %0 → ZIO[-Has[=package::Console::Service],+Throwable,+0]]): repl.Session::repl.Session.App28::repl.Session.App28.SyncValidation[=λ %0 → ZIO[-Has[=package::Console::Service],+Throwable,+0]])) ((basics.md:970))
// make[{type.repl.Session::repl.Session.App28::repl.Session.App28.Interaction[=λ %1:0 → ZIO[-Has[=package::Console::Service],+Throwable,+1:0]]}].from(call(izumi.distage.model.providers.ProviderMagnet$$$Lambda$17180/0x00000008427ff840@1527f69c(): repl.Session::repl.Session.App28::repl.Session.App28.RealInteractionZIO)) ((basics.md:1015))
// make[{type.cats.effect.Sync[=λ %0 → ZIO[-Has[=package::Console::Service],+Throwable,+0]]}].from(value(zio.interop.CatsConcurrent@3290d922: cats.effect.Sync[=λ %0 → ZIO[-Has[=package::Console::Service],+Throwable,+0]])) ((basics.md:972))

def chooseInterpreters(isDummy: Boolean) = {
  val interpreters = if (isDummy) SyncInterpreters[RIO[Console, ?]]
                     else         RealInterpretersZIO
  val module = ProgramModule[RIO[Console, ?]] ++ interpreters
  Injector().produceGetF[RIO[Console, ?], TaglessProgram[RIO[Console, ?]]](module)
}

// execute

chooseInterpreters(true)
// res30: izumi.distage.model.definition.DIResource.DIResourceBase[zio.ZIO[zio.Has[Console.Service], Throwable, β$5$], TaglessProgram[zio.ZIO[zio.Has[Console.Service], Throwable, β$6$]]] = izumi.distage.model.definition.DIResource$$anon$10@514b42e1

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

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

Or use Tag.auto.T to abstract over any kind:

class MonadTransModule[F[_[_], _]: Tag.auto.T] extends ModuleDef
class TrifunctorModule[F[_, _, _]: Tag.auto.T] extends ModuleDef
class EldritchModule[F[+_, -_[_, _], _[_[_, _], _], _]: Tag.auto.T] extends ModuleDef

consult HKTag docs for more details.

Cats & ZIO Integration

Cats & ZIO instances and syntax are available automatically in distage-core, without wildcard imports, if your project depends on cats-core, cats-effect or zio. But distage won’t bring in cats or zio as dependencies if you don’t already depend on them. (No More Orphans blog post details how that works)

Cats Resource & ZIO ZManaged Bindings also work out of the box without any magic imports.

Example:

import cats.syntax.semigroup._
import cats.effect.{ExitCode, IO, IOApp}
import distage.{DIKey, Roots, Injector}

trait AppEntrypoint {
  def run: IO[Unit]
}

object Main extends App {
  def run(args: List[String]): IO[ExitCode] = {
    
    // `distage.Module` has a Monoid instance

    val myModules = ProgramModule[IO] |+| SyncInterpreters[IO]

    val plan = Injector().plan(myModules, Roots(DIKey[AppEntrypoint]))

    for {
      // resolveImportsF can effectfully add missing instances to an existing plan
      // (You can also create instances effectfully inside `ModuleDef` via `make[_].fromEffect` bindings)

      newPlan <- plan.resolveImportsF[IO] {
        case i if i.target == DIKey[DBConnection] =>
           DBConnection.create[IO]
      }

      // `produceF` specifies an Effect to run in.
      // Effects used in Resource and Effect Bindings 
      // should match the effect in `produceF`

      _ <- Injector().produceF[IO](newPlan).use {
        classes =>
          classes.get[AppEntrypoint].run
      }
    } yield ExitCode.Success
  }
}