whyor

package module
v0.12.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 10, 2026 License: MIT Imports: 1 Imported by: 0

README

whyor

Declare the graph. Generate the wiring. Ship ordinary Go.

Compile-time dependency injection for Go, inspired by Google Wire.

CI Release Go Go Reference

No runtime DI container · No reflection · Inspectable generated code

Quick start · API docs · CLI · Releases · From Wire

How whyor turns constructors and an injector into plain Go

See it work

Why whyor?

Your constructors already describe their dependencies. whyor connects them and writes the initialization code you would otherwise maintain by hand.

  • Plain Go output. Review, debug and commit the generated injector.
  • Explicit dependencies. Constructors stay ordinary functions, independent of the generator.
  • Early feedback. Generation rejects missing providers, duplicate bindings and dependency cycles.
  • Less boilerplate. Reusable sets, generic bindings, struct construction and field extraction.
  • Beyond basic wiring. Slice providers, automatic interface bindings, Close() cleanup and graph exports.

Google Wire was archived in August 2025. whyor explores a new API for the same compile-time approach; it is not a drop-in replacement or an official continuation. The project is pre-1.0: expect API changes and check the limitations below before migrating.

Install

go install github.com/Medzoner/whyor/cmd/whyor@latest

In your application module:

go get github.com/Medzoner/whyor@latest

Current releases require Go 1.27.1+. Build the generator with a Go version at least as recent as your application's version. Add $(go env GOPATH)/bin to your PATH if whyor is not found, or use your configured GOBIN.

Prebuilt binaries are available from GitHub Releases. Starting with v0.8.0, each release includes SHA256SUMS for verifying downloaded binaries. For reproducible installs, replace @latest with a specific tag.

Releases

See CHANGELOG.md for changes and upgrade notes. Releases use version tags; a tag triggers validation, cross-platform builds and publication of binaries and checksums. Development commits on main are not releases.

Quick start

The following three files form a complete, runnable example inside a Go module.

1. Write ordinary constructors

app.go

package main

type Config struct{ Name string }

type Store interface{ Message() string }

type MemoryStore struct{ cfg *Config }

func (s *MemoryStore) Message() string { return "Hello, " + s.cfg.Name }

func NewConfig(name string) *Config { return &Config{Name: name} }
func NewStore(cfg *Config) *MemoryStore { return &MemoryStore{cfg: cfg} }

type App struct{ Store Store }

func NewApp(store Store) *App { return &App{Store: store} }
2. Declare the injector

wire.go — the filename is a convention; the build tag is what matters.

//go:build whyor

package main

import "github.com/Medzoner/whyor"

var Providers = whyor.Set(
	NewConfig,
	NewStore,
	whyor.Bind[Store, *MemoryStore](),
)

func InitApp(name string) *App {
	panic(whyor.Build(Providers, NewApp))
}

Injector parameters are supplied by the caller. Everything else comes from the providers. The panic is a declaration marker, not runtime wiring: this file is excluded from a normal build.

3. Generate and run

main.go

package main

import "fmt"

func main() {
	fmt.Println(InitApp("Go").Store.Message())
}
whyor gen .
go run .
# Hello, Go

The generated whyor_gen.go contains regular constructor calls:

// Code generated by whyor. DO NOT EDIT.

//go:build !whyor

package main

func InitApp(name string) *App {
	v1 := NewConfig(name)
	v2 := NewStore(v1)
	v3 := NewApp(v2)
	return v3
}

Commit the generated file. Normal builds no longer need to run whyor. Keep constructors in files without the whyor build tag: the generator does not copy their definitions into the generated file.

API at a glance

Declaration Purpose
Build(...) Declare an injector with panic(whyor.Build(...)).
Set(...) Group providers and options into a reusable set.
Bind[I, T]() Supply interface I using a provider for concrete type T.
Value[T](v) Supply an expression as a dependency of type T.
Struct[T](fields...) Construct T and/or *T from field dependencies.
FieldsOf[T]("A", "B") Expose named fields of a provided struct or pointer.
Many[T](providers...) Construct a []T from multiple providers.
AutoBind[T]() Select T for requested interfaces it implements, when unambiguous.
Closer[T]() Register T.Close() as cleanup for a provider without its own cleanup.
Cleanup A func(context.Context) error type for explicit, error-aware shutdown.
Collect implementations into a slice
whyor.Many[Handler](NewUsersHandler, NewOrdersHandler)
// Provides []Handler in declaration order.

Many elements are not automatically registered as standalone dependencies. If another constructor needs *UsersHandler, register its provider outside Many too. A shared function provider is called once per injector.

Bind interfaces automatically
whyor.Set(NewPostgres, whyor.AutoBind[*Postgres]())

The concrete type still needs a provider. Automatic binding succeeds only when exactly one registered AutoBind type implements the requested interface. Use explicit Bind declarations when you want to control the choice.

Instantiate generic providers

Generic constructors are supported when every type argument is explicit:

var Repositories = whyor.Set(
	NewRepository[User],
	NewRepository[Order],
	NewPair[User, Order],
)

The generator emits calls such as NewRepository[User](...). Go checks the constraints; whyor resolves the instantiated constructor's dependencies. No type argument inference or automatic search for generic instantiations is performed.

Each function instantiation is called once per injector. Different type arguments stay distinct, even when they produce the same result type. Use Many to collect such results; otherwise the usual duplicate-provider rule applies. Alias-equivalent arguments identify the same instantiation.

Construct structs and expose configuration fields
whyor.Struct[Dependencies]()              // exported fields, except whyor:"-"
whyor.Struct[Dependencies]("Store", "Log") // only the named fields
whyor.FieldsOf[*Config]("Addr", "Port")   // provides the field types

Struct[T]() and Struct[T]("*") use the same default field selection. If both T and *T are requested, they are constructed independently. Fields exposed by FieldsOf must have distinct types, or they collide as providers.

Types are matched using Go's identity rules, including aliases nested in signatures, structs and generic type arguments. Distinct defined types are not merged, even if their underlying types match.

Errors and cleanup

Providers and injectors support these result shapes:

T
(T, error)
(T, func())
(T, func(), error)
(T, whyor.Cleanup)
(T, whyor.Cleanup, error)

If a reachable provider returns an error or cleanup, the injector must expose the corresponding result too. Cleanups run in reverse acquisition order: on success the caller receives a combined cleanup; on a provider error, previously acquired resources are released before returning.

// Inside a function that returns an error:
app, cleanup, err := InitApp("production")
if err != nil {
	return err
}
defer cleanup()
_ = app // Use the initialized application.

See examples/basic for a complete cleanup-enabled injector. On error, each provider must release resources it acquired internally; the injector only calls cleanups returned by previously successful providers.

For types that already have Close() or Close() error, add whyor.Closer[*DB](). A provider's explicit cleanup takes precedence. With a legacy func() injector, errors returned by Close() are discarded; with whyor.Cleanup, they are aggregated. Cleanup functions should be non-nil on successful construction.

Shutdown with context and errors
func InitApp(ctx context.Context) (*App, whyor.Cleanup, error) {
	panic(whyor.Build(Providers, NewApp))
}

After successful initialization, call the returned cleanup with your shutdown context, for example inside a function returning an error:

app, cleanup, err := InitApp(ctx)
if err != nil {
	return err
}
_ = app // Run the application before initiating shutdown.
stopCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return cleanup(stopCtx)
  • Providers may return whyor.Cleanup, another named function type with the same underlying signature, or plain func(context.Context) error.
  • The injector must expose a context-aware cleanup if any reachable provider requires one. Legacy func() providers can be combined with it unchanged.
  • Every acquired cleanup is called in reverse order, even after a cleanup error. Errors are combined with errors.Join, preserving errors.Is / errors.As.
  • On successful initialization, your shutdown context is forwarded unchanged.
  • On failed initialization, cleanup errors are joined with the initialization error. Rollback uses context.WithoutCancel on an injector context parameter, preserving values but removing cancellation and deadlines. If there is no such parameter, it uses context.Background().
  • Rollback has no generated deadline. Cleanup implementations must bound blocking operations themselves. Shutdown deadlines are cooperative: the generator does not spawn goroutines or forcibly stop cleanup calls.
  • Cleanups are not made idempotent or concurrency-safe; the caller should invoke the combined cleanup once.

See examples/lifecycle for mixed legacy/modern cleanup, Close() error aggregation and rollback tests.

CLI

Package patterns default to ./....

Command Use
whyor gen ./... Write changed whyor_gen.go files.
whyor gen -w ./... Generate initially, then watch Go files under the current directory.
whyor check ./... Exit nonzero if generated code is stale or generation fails.
whyor unused ./... List function providers declared in injectors but never called by any analyzed injector; exit nonzero if found.
whyor show ./... Display dependency trees.
whyor show -f mermaid ./... Export Mermaid graphs.
whyor show -f dot ./... Export Graphviz graphs.
whyor show -f json ./... Export a versioned document containing all matching injectors.
whyor init ./internal/app Create a declaration skeleton without overwriting wire.go.
Understand your dependency graph
InitApp
└── *App [NewApp]
    └── Store [Bind]
        └── *PG [NewPG]
            └── *Config [NewConfig]
                └── string [parameter dsn]

Repeated dependencies are marked (*) in the tree. Graph output is useful for code reviews and architecture documentation. With Graphviz installed:

whyor show -f dot ./internal/app | dot -Tsvg > dependencies.svg
Integrate with your tools
whyor show -f json ./... > dependencies.json

The JSON document contains version: 1 and a graphs array. Each graph has its package, injector, source position, root node ID, nodes and edges. Nodes identify their type and provider (or injector parameter); source positions are included where available. Edges point from a consumer to its dependency. Node IDs are local to each injector, not persistent identifiers across code changes. Positions use the paths reported by the Go loader, which can be absolute.

An invalid injector returns an error rather than partial JSON. No matching injectors produces an empty graphs array.

Follow a failed resolution

Errors include the path from the injector's result to the dependency that cannot be built, including provider and binding locations:

wire.go:20:8: Init: no provider for *DB (needed by *Postgres)
    dependency path:
      *Server [NewServer] at providers.go:10:6
      → *App [NewApp] at providers.go:9:6
      → Store [Bind] at wire.go:20:50
      → *Postgres [NewPostgres] at providers.go:8:6
      → *DB

Ambiguous automatic bindings name the candidate types and suggest an explicit Bind, rather than reporting a misleading missing provider. Duplicate providers report both source positions.

Automate generation

Place the directive in a file without the whyor tag:

//go:generate whyor gen .
go generate ./...

For CI, after installing the generator:

go test ./...
whyor check ./...
whyor unused ./...

check verifies freshness; it does not replace compilation and tests.

Migrating from Wire

The model is familiar; the declaration API is different.

Wire whyor
wire.NewSet(...) whyor.Set(...)
wire.Bind(new(Store), new(*PG)) whyor.Bind[Store, *PG]()
wire.Struct(new(Deps), "*") whyor.Struct[Deps]()
wire.FieldsOf(new(*Config), "Addr") whyor.FieldsOf[*Config]("Addr")
//go:build wireinject //go:build whyor
wire_gen.go whyor_gen.go

whyor also offers Many, AutoBind, Closer, watch mode and Mermaid/Graphviz exports. It does not claim full compatibility with Wire.

Read the migration guide for the checklist and behavior differences.

Examples

Example Demonstrates
showcase Runnable hello application, interface binding and demonstrative cleanup.
basic Sets, interface binding, cleanup and go generate.
features Many, AutoBind and Closer.
generics Explicit generic providers, imported constructors, multiple type arguments, sharing and cleanup.
lifecycle Context-aware cleanup, error aggregation, legacy adaptation and failed initialization.
structs Selected struct fields and FieldsOf.
alias Matching an alias and its target type.
typeidentity Nested aliases, equivalent interfaces, instantiated generic types and shared dependencies.
edge Import-name collisions, values and error-path cleanup.

Current limitations

See generation contracts and v1.0 readiness for verified guarantees, output-file ownership and remaining stabilization work.

  • Providers must be plain, non-variadic functions. Generic providers require all type arguments to be supplied explicitly; methods are unsupported.
  • Injectors must be non-generic and non-variadic functions.
  • Injectors must contain the declaration panic(whyor.Build(...)) as their only statement.
  • Injector parameters must not shadow predeclared Go identifiers such as error, nil or new.
  • Generated code calls providers; it does not copy helpers from tagged files.
  • Many does not accept nested Many, Bind, AutoBind or Closer declarations.
  • Dependency resolution is type-based: multiple providers of the same type conflict outside Many.
  • Watch mode polls every 500 ms under the current directory and excludes generated Go files, vendor, testdata and hidden directories.
  • Graph exports and diagnostics are evolving alongside the pre-1.0 API.

Contributing

git clone https://github.com/Medzoner/whyor.git
cd whyor
make install
make check

Tests include versioned generated examples, invalid declaration fixtures, graph output assertions and reproducible randomized provider graphs. For a change to generation behavior, add an example or regression test and regenerate the expected output.

Found a bug or have a proposal? Open an issue. Read CONTRIBUTING.md for reproductions, tests and PR expectations.

License

MIT.

Documentation

Overview

Package whyor provides declarations for compile-time dependency injection in Go. It is an independent, pre-1.0 alternative inspired by Google Wire, not an official continuation or a drop-in replacement.

How it works

Constructors are ordinary Go functions. Their parameters describe dependencies and their results describe the values they provide. The whyor CLI analyzes injector declarations and writes whyor_gen.go with regular constructor calls. There is no runtime dependency-injection container or reflection-based lookup.

Injector declarations belong in files guarded by the whyor build tag:

//go:build whyor

package app

import "github.com/Medzoner/whyor"

var Providers = whyor.Set(NewConfig, NewStore, whyor.Bind[Store, *MemoryStore]())

func InitApp(name string) *App {
	panic(whyor.Build(Providers, NewApp))
}

The constructors and application types in this illustration are defined in ordinary, untagged files. The declaration's panic is a generation marker, not an application startup strategy. Generated files use the !whyor tag.

CLI and installation

Install the CLI separately from the declaration package:

go install github.com/Medzoner/whyor/cmd/whyor@latest
go get github.com/Medzoner/whyor@latest
whyor gen ./...
go test ./...
whyor check ./...

Commit generated files so normal builds need not run the generator. Current releases require Go 1.27.1 or newer; the generator must be built with a Go version at least as recent as the target application's version.

The CLI also supports dependency graph exports (tree, JSON, DOT and Mermaid), unused-provider checks, a declaration skeleton and a polling watch mode.

Declarations

Set groups reusable providers. Bind explicitly selects an implementation for an interface, while AutoBind opts into unambiguous automatic binding. Value provides a typed expression; Struct constructs structs and FieldsOf exposes configuration fields. Many provides a slice of implementations. Generic provider functions require explicit instantiation, such as NewStore[User].

Cleanup

Providers can return T, (T, error), (T, func()), (T, func(), error), or the corresponding forms using Cleanup. Acquired cleanups execute in reverse order. Modern Cleanup callbacks receive the caller's shutdown context and aggregate errors. Closer can register an existing Close method.

Rollback strips acquisition cancellation and deadlines; no implicit timeout, idempotency or concurrency safety is added. Cleanup implementations must bound blocking operations themselves. A failing provider owns its partial resources.

Examples and migration

Start with the runnable demo, complete examples and Wire migration guide. The generation contracts document records verified guarantees and deliberate limitations. API signatures and behavior may evolve before v1.0.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Build

func Build(opts ...Option) any

Build declares an injector body. It must be the argument of panic in an injector function. It is replaced by generated code.

Types

type Cleanup added in v0.10.0

type Cleanup func(context.Context) error

Cleanup releases resources using a caller-supplied shutdown context. Generated cleanup calls run in reverse acquisition order and aggregate errors.

type Option

type Option any

Option is a provider, a Set, a Bind or a Value accepted by Build and Set. Plain provider functions are accepted too.

func AutoBind

func AutoBind[T any]() Option

AutoBind makes T usable wherever an interface it implements is needed, as long as exactly one registered AutoBind type implements that interface.

func Bind

func Bind[I, T any]() Option

Bind tells the generator that interface I is satisfied by concrete type T.

func Closer

func Closer[T any]() Option

Closer registers T's Close method as its cleanup: the injector must return func() or Cleanup. Close errors are preserved with Cleanup, discarded with func(). It applies to providers of T that have no cleanup of their own.

func FieldsOf added in v0.2.0

func FieldsOf[T any](fields ...string) Option

FieldsOf provides the named fields of T (a struct or pointer to struct) as dependencies of their own types.

func Many

func Many[T any](opts ...Option) Option

Many provides a []T made of the given providers, each returning a value assignable to T. Its elements are not provided as T on their own.

func Set

func Set(opts ...Option) Option

Set groups providers and options so they can be reused.

func Struct added in v0.2.0

func Struct[T any](fields ...string) Option

Struct provides both T and *T by filling fields of struct T with dependencies. With no argument (or "*"), every exported field not tagged `whyor:"-"` is filled; otherwise only the named exported fields are.

func Value

func Value[T any](v T) Option

Value provides the given expression as a dependency of type T.

Directories

Path Synopsis
cmd
whyor command
Command whyor generates dependency injection code.
Command whyor generates dependency injection code.
examples
showcase command
internal
gen
Package gen implements the whyor code generator.
Package gen implements the whyor code generator.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL