Skip to content

Latest commit

 

History

History
617 lines (437 loc) · 19.9 KB

wire.md

File metadata and controls

617 lines (437 loc) · 19.9 KB
id wire
title Wire

Wire[-In, +Out] is a compile-time safe recipe for constructing a service and its dependencies. Wires describe how to construct an Out value given access to its dependencies via a Context[In] and a Scope for finalization:

sealed trait Wire[-In, +Out] {
  def isShared: Boolean
  def isUnique: Boolean = !isShared

  def shared: Wire.Shared[In, Out]
  def unique: Wire.Unique[In, Out]

  def toResource(deps: Context[In]): Resource[Out]
}

The type parameters are:

  • In (contravariant): the dependencies required to construct the service
  • Out (covariant): the service produced

Wires are the building blocks of dependency injection in Scope. They form the foundation for constructor-based dependency injection via Resource.from[T](wires*).

Overview

A Wire built with Wire.shared or Wire.unique is a lazy recipe, not an execution. It holds a construction function (Scope, Context[In]) => Out and a sharing strategy — either Shared (reference-counted via Resource.shared) or Unique (fresh instance per allocation). Such a Wire does nothing until you convert it to a Resource and allocate it within a scope. Wire(value) is the exception: a known bug in 0.0.56 evaluates value when the Wire is created, not when it is allocated.

Here's the typical flow:

Wire (recipe)
  ↓
Resource (lazy, composable)
  ↓
scope.allocate(...)
  ↓
$[T] (scoped value in scope)

Motivation

Without Wires, building a multi-layer application requires manual dependency passing:

import zio.blocks.scope._

final case class Config(dbUrl: String)

final class Database(config: Config) extends AutoCloseable {
  def close(): Unit = println(s"closing connection to ${config.dbUrl}")
}

final class UserService(db: Database) {
  def getUser(id: Int): String = s"user $id"
}

final class App(service: UserService) {
  def run(): Unit = println(service.getUser(1))
}

// Manual wiring:
Scope.global.scoped { scope =>
  val config = Config("jdbc:postgres://localhost/db")
  val db = new Database(config)
  scope.defer(db.close())
  val service = new UserService(db)
  new App(service).run()
}

Manual wiring must build every object by hand and register each close() itself with Scope#defer. A value allocated through Resource#allocate is scoped and cannot be passed as a constructor argument, so manual wiring either builds plain values and defers each close(), or composes Resources with Resource#map and Resource#flatMap.

With Wire + Resource.from, the macro handles the dependency graph:

Scope.global.scoped { scope =>
  import scope._
  val app = Resource.from[App](
    Wire(Config("jdbc:postgres://localhost/db"))
  ).allocate
  $(app)(_.run())
}

:::note Write a Resource.from as a def, not a val. A known bug in 0.0.56: a Resource.from[T] stored in a val works in its first scope and then fails on a second use with IllegalStateException: Cannot allocate from a destroyed shared resource. :::

Benefits:

  • Compile-time graph validation — missing dependencies and duplicate providers are reported at compile time; a dependency cycle is not (see the note below)
  • Automatic finalization — AutoCloseable resources are finalized in LIFO order
  • Sharing control — choose which services are singletons (shared) vs fresh per allocation (unique)
  • Type-safe construction — no stringly-typed dependency resolution

Installation

Add the following dependency to your build.sbt:

// ZIO Blocks scope module
libraryDependencies += "dev.zio" %% "zio-blocks-scope" % "@VERSION@"

For cross-platform (Scala.js):

// ZIO Blocks scope module
libraryDependencies += "dev.zio" %%% "zio-blocks-scope" % "@VERSION@"

Supported Scala versions: 3.9.x and 3.10.x.

Construction

Wire provides multiple ways to create instances, ranging from automatic macro-based derivation to manual construction for custom logic. Here are the main construction methods:

Wire.shared[T] — derive a shared wire

The Wire.shared[T] macro inspects T's primary constructor and generates a shared wire that reuses the same instance across dependents:

import zio.blocks.scope._
import zio.blocks.context.Context

final case class Config(debug: Boolean)

final class Database(config: Config) extends AutoCloseable {
  def query(sql: String): String = s"[db] $sql"
  def close(): Unit = println("database closed")
}

val wire: Wire.Shared[Config, Database] = Wire.shared[Database]

Scope.global.scoped { scope =>
  import scope._
  val config = Config(debug = true)
  val deps = Context[Config](config)
  val db = allocate(wire.toResource(deps))
  $(db)(_.query("SELECT 1"))
}

Wire.unique[T] — derive a unique wire

Like Wire.shared[T], but its resource is unique: each allocation builds a fresh instance. Use for request-scoped or per-call services. A known bug in 0.0.56: Resource.from does not always respect a wire's sharing. On Scala 3 it treats every explicit wire as shared, so a unique wire gives one instance to every dependent. On Scala 2 it reads the wire's static type, so a shared wire typed as plain Wire gives each dependent its own instance; keep shared wires typed as Wire.Shared. The example below uses Wire#toResource, where each allocation builds a fresh instance on both versions:

import zio.blocks.scope._
import zio.blocks.context.Context

final class RequestHandler {
  val id = scala.util.Random.nextInt()
}

val wire: Wire.Unique[Any, RequestHandler] = Wire.unique[RequestHandler]

Scope.global.scoped { scope =>
  import scope._
  val deps = Context.empty
  val resource = wire.toResource(deps)

  val h1 = allocate(resource)
  val h2 = allocate(resource)

  $(h1)(_.id) != $(h2)(_.id)
}

Wire.apply[T] — lift a pre-existing value

Creates a shared wire that injects a value you already have. If the value is AutoCloseable, its close() method is automatically registered as a finalizer:

import zio.blocks.scope._
import zio.blocks.context.Context

final case class Config(dbUrl: String)

val config = Config("jdbc:postgres://localhost/db")
val wire: Wire.Shared[Any, Config] = Wire(config)

Scope.global.scoped { scope =>
  import scope._
  val cfg = allocate(wire.toResource(Context.empty))
  $(cfg)(_.dbUrl)
}

Wire.Shared.fromFunction — manual shared wire construction

Use this for custom construction logic when macro derivation doesn't fit. Unlike Wire.shared[T], Wire.Shared.fromFunction does not register close() for an AutoCloseable result (a known bug in 0.0.56). Register it inside the function with scope.defer, on the Scope the function receives:

import zio.blocks.scope._
import zio.blocks.context.Context

final case class Config(timeout: Int)

final class Client(config: Config) extends AutoCloseable {
  def call(): String = s"calling with timeout=${config.timeout}"
  def close(): Unit  = println("client closed")
}

val wire: Wire.Shared[Config, Client] =
  Wire.Shared.fromFunction { (scope, ctx) =>
    val config = ctx.get[Config]
    val client = new Client(config)
    scope.defer(client.close())
    client
  }

Scope.global.scoped { scope =>
  import scope._
  val config = Config(30)
  val deps = Context[Config](config)
  val client = allocate(wire.toResource(deps))
  $(client)(_.call())
}

Wire.Unique.fromFunction — manual unique wire construction

Like Wire.Shared.fromFunction, but for unique wires. Wire.Unique.fromFunction does not register close() for an AutoCloseable result either (a known bug in 0.0.56), so register it inside the function with scope.defer. The example below returns a plain class, which needs no cleanup:

import zio.blocks.scope._
import zio.blocks.context.Context

final class RequestContext {
  val id = scala.util.Random.nextInt()
}

val wire: Wire.Unique[Any, RequestContext] =
  Wire.Unique.fromFunction { (_, _) =>
    new RequestContext
  }

Scope.global.scoped { scope =>
  import scope._
  val deps = Context.empty
  val resource = wire.toResource(deps)

  val r1 = allocate(resource)
  val r2 = allocate(resource)

  $(r1)(_.id) != $(r2)(_.id)
}

Shared vs Unique

The fundamental difference is reuse semantics:

Aspect Shared Unique
Construction Wire.shared[T] macro or Wire.Shared.fromFunction Wire.unique[T] macro or Wire.Unique.fromFunction
Resource type Resource.shared[T] (reference-counted) Resource.unique[T] (fresh per call)
When to use Singletons, expensive resources (connections, thread pools) Request scoped, stateful per-call (request handlers)
Instance reuse Same instance across entire dependency graph New instance per allocation
Finalization Runs when last referencing scope closes Runs when each scope closes

A known bug in 0.0.56 breaks this table inside Resource.from: on Scala 3 an explicit unique wire is shared across the graph, and on Scala 2 a shared wire whose static type is plain Wire gives each dependent its own instance. Wire#toResource follows the table on both versions.

In the diamond pattern (where App depends on both UserService and OrderService, both of which depend on Database), a shared wire ensures Database is constructed once and both services receive the same instance:

import zio.blocks.scope._

final class Database {
  val id = scala.util.Random.nextInt()
}

final class UserService(db: Database) {
  def getDbId(): Int = db.id
}

final class OrderService(db: Database) {
  def getDbId(): Int = db.id
}

final class App(userService: UserService, orderService: OrderService) {
  def check(): Boolean = {
    // With shared Database, these should be equal
    userService.getDbId() == orderService.getDbId()
  }
}

// Using shared wires for all dependencies
def resource = Resource.from[App](
  Wire.shared[Database],
  Wire.shared[UserService],
  Wire.shared[OrderService]
)

Scope.global.scoped { scope =>
  import scope._
  val app = resource.allocate
  $(app)(_.check())
}

Core Operations

The Wire interface provides a set of operations for inspecting and transforming wires:

Wire#isShared and Wire#isUnique

Check the sharing strategy of a wire:

trait Wire[-In, +Out] {
  def isShared: Boolean
  def isUnique: Boolean = !isShared
}

Here's how to use these methods:

import zio.blocks.scope._

final class Greeter

val sharedWire = Wire.shared[Greeter]
val uniqueWire = Wire.unique[Greeter]

Each wire reports its strategy:

println(s"sharedWire.isShared: ${sharedWire.isShared}")
println(s"sharedWire.isUnique: ${sharedWire.isUnique}")
println(s"uniqueWire.isShared: ${uniqueWire.isShared}")
println(s"uniqueWire.isUnique: ${uniqueWire.isUnique}")

Wire#shared and Wire#unique — convert between strategies

Convert a wire to the opposite strategy:

trait Wire[-In, +Out] {
  def shared: Wire.Shared[In, Out]
  def unique: Wire.Unique[In, Out]
}

To convert between sharing strategies:

val original = Wire.shared[Greeter]

val converted: Wire.Unique[Any, Greeter] = original.unique

// Converting back returns a new shared wire
val backToShared: Wire.Shared[Any, Greeter] = converted.shared

The original stays shared, the converted wire is unique, and converting back yields a shared wire again:

println(s"original.isShared: ${original.isShared}")
println(s"converted.isUnique: ${converted.isUnique}")
println(s"backToShared.isShared: ${backToShared.isShared}")

Calling shared on an already-shared wire returns this (identity); likewise unique on a unique wire returns this.

Wire#toResource — convert a wire to a Resource

Converts the wire to a lazy Resource by providing the dependency context:

trait Wire[-In, +Out] {
  def toResource(deps: Context[In]): Resource[Out]
}

Config takes a String, so the wire needs a Context[String]:

import zio.blocks.scope._
import zio.blocks.context.Context

final case class Config(value: String)

val wire = Wire.shared[Config]
val deps = Context[String]("hello")

val resource: Resource[Config] = wire.toResource(deps)

Scope.global.scoped { scope =>
  import scope._
  val cfg = allocate(resource)
  $(cfg)(_.value)
}

Wire#make — construct directly from a wire

Directly construct a value without going through Wire#toResource. This is a low-level operation; prefer allocate(wire.toResource(...)) for safety:

trait Wire.Shared[-In, +Out] {
  def make(scope: Scope, context: Context[In]): Out
}

Here's how to use this method:

import zio.blocks.scope._
import zio.blocks.context.Context

final class Service {
  def getName: String = "service"
}

val wire = Wire.shared[Service]

Scope.global.scoped { scope =>
  import scope._
  val service = wire.make(scope, Context.empty)
  println(service.getName)
}

Macro Derivation

When you call Wire.shared[T] or Wire.unique[T], the macro performs these checks:

  1. Is T a class? — traits and abstract classes are rejected; only concrete classes can be auto-wired.
  2. Does T have a primary constructor? — the macro inspects constructor parameters to determine dependencies.
  3. Is each parameter either a dependency type or a special injected type? — parameters of type Scope or Finalizer are recognized and injected automatically; others are looked up in the context.
  4. Does T extend AutoCloseable? — if yes, close() is automatically registered as a finalizer in the scope.

Example with all three features:

import zio.blocks.scope._

final case class Config(dbUrl: String)

final class Logger(implicit finalizer: Finalizer) {
  def log(msg: String): Unit = println(msg)
}

final class Database(config: Config)(implicit scope: Scope) extends AutoCloseable {
  def connect(): Unit = {
    scope.defer(println("database connection closed"))
    println(s"connecting to ${config.dbUrl}")
  }

  def query(sql: String): String = s"result: $sql"

  def close(): Unit = println("database closed")
}

final class Service(db: Database, logger: Logger) {
  def run(): Unit = {
    logger.log(db.query("SELECT 1"))
  }
}

// Macro handles Finalizer injection, Scope injection, and AutoCloseable registration
val wire = Wire.shared[Service]

What happens with subtype conflicts

If a constructor has dependencies of related types (e.g., both FileInputStream and InputStream), the macro rejects the wire because Context is type-indexed and cannot reliably disambiguate. For example:

import zio.blocks.scope._
import java.io.{FileInputStream, InputStream}

final class Copier(input: InputStream, fileInput: FileInputStream)

// does not compile: the macro reports "Dependency type conflict in Copier"
// and "java.io.FileInputStream is a subtype of java.io.InputStream."
val copierWire = Wire.shared[Copier]

To fix this, wrap one of the types to make it distinct:

import zio.blocks.scope._
import java.io.{FileInputStream, InputStream}

final case class FileInputWrapper(value: FileInputStream)

final class Copier(input: InputStream, fileInput: FileInputWrapper)

val copierWire = Wire.shared[Copier]

Integration with Resource.from

Wire is designed for use with Resource.from[T](wires*), which performs whole-graph dependency injection:

import zio.blocks.scope._

final case class AppConfig(dbUrl: String)

final class Database(config: AppConfig) extends AutoCloseable {
  def query(sql: String): String = s"result: $sql"
  def close(): Unit = ()
}

final class Repository(db: Database) {
  def query(): String = db.query("SELECT *")
}

final class Service(repo: Repository) extends AutoCloseable {
  def run(): String = repo.query()
  def close(): Unit = ()
}

final class App(service: Service) {
  def run(): String = service.run()
}

// Provide only the leaf dependency; Resource.from derives the rest
def appResource: Resource[App] = Resource.from[App](
  Wire(AppConfig("jdbc:postgres://localhost/db"))
)

appResource.use(_.run())

When Resource.from composes wires, it respects the sharing strategy:

  • Shared wires → reference-counted (single instance in the graph)
  • Unique wires → fresh per allocation

A known bug in 0.0.56: on Scala 3, an explicit unique wire is also built once and shared across the graph. Scala 2 follows the wire's static type, so a shared wire stored as a plain Wire[In, Out] gives each dependent its own instance.

The macro reports missing dependencies and duplicate providers at compile time. For what each error looks like and how to fix it, see How to Fix Common Scope and Wire Compile Errors.

A known bug in 0.0.56: a dependency cycle does not produce a cycle error. The Resource.from macro crashes instead (#1767), so do not rely on cycle detection yet.

The AppConfig leaf above is hardcoded, which is rarely what a real graph wants. Config.wire[A] produces a Wire.Shared[ConfigSource, A] that decodes A from an injected ConfigSource, so configuration becomes a node in the graph rather than something resolved before it — see Config. For a complete walkthrough, see How to Feed Configuration into a Wire Dependency Graph.

Comparison with Alternatives

Feature Wire Manual Passing Service Locator
Type safety ✓ (compile-time validation) ✓ (implicit) ✗ (string keys)
Cycle detection ✗ (a cycle crashes the macro in 0.0.56) ✗ ✗ (runtime)
Sharing semantics ✓ (configurable) Manual ✓ (singleton pattern)
Finalization ✓ (LIFO, automatic) Manual Manual
Performance ~0 overhead (macro-generated) ~0 overhead ~1 allocation overhead

Coming from ZLayer or macwire? Coming from cats-effect Resource, ZIO Scope/ZLayer, macwire or Using maps ZLayer.make, ZLayer.fromFunction, wire[A] and autowire onto Resource.from and Wire.

Running the Examples

All code from this guide is available as runnable examples in the scope-examples module.

1. Clone the repository and navigate to the project:

git clone https://github.com/zio/zio-blocks.git
cd zio-blocks

2. Run individual examples with sbt:

Basic wire construction demonstrates how to create and use Wire for dependency injection. View the example source code:

import docs.SourceFile

SourceFile.print("scope-examples/src/main/scala/wire/WireBasicExample.scala")

(source)

Run this example with:

cd scope-examples && sbt "runMain wire.wireBasicExample"

Comparing shared vs unique semantics shows how shared wires reuse the same instance across dependents, while unique wires create fresh instances. View the example:

import docs.SourceFile

SourceFile.print("scope-examples/src/main/scala/wire/WireSharedUniqueExample.scala")

(source)

Run this example with:

cd scope-examples && sbt "runMain wire.wireSharedUniqueExample"

Manual wire construction demonstrates how to use fromFunction for custom construction logic. View the example:

import docs.SourceFile

SourceFile.print("scope-examples/src/main/scala/wire/WireFromFunctionExample.scala")

(source)

Run this example with:

cd scope-examples && sbt "runMain wire.wireFromFunctionExample"