di

package
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2026 License: MIT Imports: 24 Imported by: 0

README

di

Declarative wiring for Uber Fx. di is built for teams that want consistent composition patterns, easy graph introspection, and clean test overrides without hand-editing Fx options.

== Installation ==

go get github.com/bronystylecrazy/ultrastructure/di

== How We Use It ==

  • Build the graph with small, composable nodes (Provide, Invoke, Module).
  • Keep wiring close to the boundary (modules), keep business logic in constructors.
  • Use Plan during reviews to see what gets wired and why.
  • Prefer Replace/Default for tests over ad-hoc conditional wiring.

== Core Vocabulary ==

  • Node – a declarative unit such as Provide, Invoke, Module, Replace.
  • App – a tree of nodes. di.App(...).Build() returns an fx.Option.
  • Plan – a structured view of the wiring graph (di.Plan(...)).

== Quick Start ==

package main

import (
	"fmt"

	"github.com/bronystylecrazy/ultrastructure/di"
	"go.uber.org/fx"
)

type Store struct {
	Ready bool
}

func NewStore() *Store { return &Store{} }
func MarkStoreReady(s *Store) *Store {
	// Decorators can mutate or replace instances.
	s.Ready = true
	return s
}
func PrintStoreReady(s *Store) {
	// Invokes run after the graph is built.
	fmt.Println("store ready:", s.Ready)
}

func main() {
	app := fx.New(
		di.App(
			di.Provide(NewStore),
			di.Decorate(MarkStoreReady),
			di.Invoke(PrintStoreReady),
		).Build(),
	)
	_ = app.Start(nil)
}

Result of execution:

store ready: true

== Common Patterns ==

=== Param Tags ===

Use Params to tag positional parameters on Provide, Invoke, and Decorate.

type Service struct {
	DB string
}

func NewPrimaryDB() string { return "primary" }
func NewTestDB() string    { return "test" }
func NewService(db string) *Service {
	// Params let you control which named input is used.
	return &Service{DB: db}
}
func PrintServiceDB(s *Service) {
	// Simple verification output.
	fmt.Println("service db:", s.DB)
}

// imports: fmt
di.App(
	di.Provide(NewPrimaryDB, di.Name("primary")),
	di.Provide(NewTestDB, di.Name("test")),
	di.Provide(NewService, di.Params(di.Name("test"))),
	di.Invoke(PrintServiceDB),
).Build()

Result of execution:

service db: test

=== Replace & Default ===

Swap implementations without reshaping your graph.

type Reader interface {
	Read() string
}

type realReader struct{}
func (realReader) Read() string { return "real" }

type mockReader struct{}
func (mockReader) Read() string { return "mock" }

func NewReader() Reader { return realReader{} }
func PrintReader(r Reader) {
	// Replace swaps the implementation.
	fmt.Println("read:", r.Read())
}

// imports: fmt
di.App(
	di.Provide(NewReader),
	di.Replace(mockReader{}),
	di.Invoke(PrintReader),
).Build()

Result of execution:

read: mock

Use ReplaceBefore / ReplaceAfter when ordering matters across modules.

func NewProdLabel() string { return "prod" }
func NewDevLabel() string  { return "dev" }
func PrintLabels(prod string, dev string) {
	// ReplaceBefore/After are order-sensitive.
	fmt.Println("prod:", prod, "dev:", dev)
}

// imports: fmt
di.App(
	di.Provide(NewProdLabel, di.Name("prod")),
	di.ReplaceBefore("nop", di.Name("prod")),
	di.Provide(NewDevLabel, di.Name("dev")),
	di.ReplaceAfter("json", di.Name("dev")),
	di.Invoke(PrintLabels, di.Params(di.Name("prod"), di.Name("dev"))),
).Build()

Result of execution:

prod: nop dev: json

=== Auto-Group ===

Collect implementations into a group without explicit Group(...) on each provider.

type Handler interface {
	Name() string
}

type handlerA struct{}
func (handlerA) Name() string { return "A" }

type handlerB struct{}
func (handlerB) Name() string { return "B" }

func NewHandlerA() Handler { return handlerA{} }
func NewHandlerB() Handler { return handlerB{} }
func PrintHandlers(handlers []Handler) {
	// AutoGroup collects implementations into a slice.
	for _, h := range handlers {
		fmt.Println("handler:", h.Name())
	}
}

// imports: fmt
fx.New(
	di.App(
		di.AutoGroup[Handler]("handlers"),
		di.Provide(NewHandlerA),
		di.Provide(NewHandlerB),
		di.Invoke(PrintHandlers, di.Group("handlers")),
	).Build(),
).Run()

Result of execution:

handler: A
handler: B

=== Populate ===

Populate local variables from the container (supports name/group tags).

type AppConfig struct {
	Name string
	Port int
}

var cfg AppConfig

func PrintConfig(cfg AppConfig) {
	// Populate writes into local variables after build.
	fmt.Println("config:", cfg.Name, cfg.Port)
}

// imports: context, fmt
app := fx.New(
	di.App(
		di.Supply(AppConfig{Name: "demo", Port: 9000}),
		di.Populate(&cfg),
	).Build(),
)
_ = app.Start(context.Background())
PrintConfig(cfg)

Result of execution:

config: demo 9000

== Config (Viper) ==

Load a config file into a typed struct.

type Config struct {
	App struct {
		Name string
	}
	Db struct {
		Host string
	}
}

func PrintConfigSummary(cfg Config) {
	// Config binds file values to a typed struct.
	log.Println(cfg.App.Name, cfg.Db.Host)
}

// imports: log
fx.New(
	di.App(
		di.Config[Config](
			"di/examples/config_toml/config.toml",
			di.ConfigType("toml"),
		),
		di.Invoke(PrintConfigSummary),
	).Build(),
).Run()

Result of execution:

demo-app db.local

Override with environment variables.

type Config struct {
	App struct {
		Name string
	}
}

func LogConfigName(cfg Config, l *zap.Logger) {
	// Env overrides land in the same struct.
	l.Info("app", zap.String("name", cfg.App.Name))
}

// imports: go.uber.org/zap
fx.New(
	di.App(
		di.Config[Config](
			"di/examples/config_env/config.toml",
			di.ConfigEnvOverride(),
		),
		di.Invoke(LogConfigName),
	).Build(),
).Run()

Result of execution:

{"level":"info","msg":"app","name":"demo-app"}

Watch and restart on changes.

type AppConfig struct {
	Name string
	Port int
}

func PrintWatchConfig(cfg AppConfig) {
	// Watch emits on changes; this prints current values.
	log.Println("config", cfg.Name, cfg.Port)
}

// imports: log
err := di.App(
	di.ConfigFile("di/examples/config_watch/config.toml", di.ConfigType("toml")),
	di.Config[AppConfig]("app", di.ConfigWatch()),
	di.Invoke(PrintWatchConfig),
).Run()

Result of execution:

config demo-app 9000

== Diagnostics ==

Enable source-aware error diagnostics.

func PrintDiagnostics(msg string) {
	// Diagnostics surfaces source-aware errors.
	log.Println(msg)
}

// imports: log
fx.New(
	di.App(
		di.Diagnostics(),
		di.Invoke(PrintDiagnostics),
	).Build(),
).Run()

Result of execution:

missing type: string (required by Invoke)

== API Reference ==

=== App and Graph ===

  • App(nodes ...any) — build a node tree; call .Build() to get fx.Option.
  • Run(nodes ...any) — build and run an app in one call.
  • Plan(nodes ...any) — render a plan string for review/debugging.

=== Wiring Nodes ===

  • Provide(constructor any, opts ...any) — register a constructor.
  • Supply(value any, opts ...any) — register a concrete value.
  • Invoke(function any, opts ...Option) — run a function on app start.
  • Decorate(function any, opts ...Option) — transform an existing value.
  • Populate(args ...any) — fill local variables from the container.
  • Module(name string, nodes ...any) — create a named module.
  • Options(items ...any) — group nodes without a name, or group options inside providers.
  • Replace(value any, opts ...any) — override a value/provider.
  • ReplaceBefore(value any, opts ...any) — override only items declared before.
  • ReplaceAfter(value any, opts ...any) — override only items declared after.
  • Default(value any, opts ...any) — supply a fallback when missing.

=== Conditionals ===

  • If(cond bool, nodes ...any) — include nodes when a boolean is true.
  • When(fn any, nodes ...any) — include nodes when fn() returns true.
  • Switch(items ...any) — choose between cases and defaults.
  • Case(cond bool, nodes ...any) — static switch case.
  • WhenCase(fn any, nodes ...any) — dynamic switch case.
  • DefaultCase(nodes ...any) — switch fallback.

=== Lifecycle ===

  • OnStart(fn any) — register an Fx OnStart hook.
  • OnStop(fn any) — register an Fx OnStop hook.

=== Auto-Group / Auto-Inject ===

  • AutoGroup[T](group ...string) — collect implementations into a group.
  • AutoGroupFilter(fn func(reflect.Type) bool) — filter auto-group targets.
  • AutoGroupAsSelf() — include the concrete type when auto-grouping.
  • AutoGroupIgnoreType[T](group ...string) — ignore auto-group for a type.
  • AutoGroupIgnore() — ignore auto-group for a specific provider.
  • AutoInject() — enable auto field injection for the scope.
  • AutoInjectIgnore() — disable auto field injection for a provider.

=== Tagging and Exports ===

  • As[T](tags ...string) — export a provider as interface/type.
  • Name(name string) — name a value.
  • Group(name string) — group a value.
  • ToGroup(name string) — send the most recent As to a group.
  • Self() / AsSelf() — export the concrete type alongside others.
  • Private() / Public() — hide or expose providers across modules.
  • Params(items ...any) — apply positional param tags.
  • InTag(tag string) — raw param tag.
  • InGroup(name string) — param group tag.
  • Optional() — mark a param optional.

=== Config (Viper) ===

  • Config[T](pathOrKey string, opts ...any) — load config into a struct.
  • ConfigFile(path string, opts ...any) — register a config file source.
  • ConfigBind[T](key string, opts ...any) — bind a key into a struct.
  • ConfigType(kind string) — set file type (toml/json/yaml).
  • ConfigName(name string) — name a config source.
  • ConfigPath(path string) — add search paths.
  • ConfigOptional() — do not error on missing config.
  • ConfigEnvPrefix(prefix string) — environment prefix.
  • ConfigEnvKeyReplacer(replacer *strings.Replacer) — env key mapping.
  • ConfigEnvOverride(prefix ...string) — enable env overrides.
  • ConfigAutomaticEnv() — viper automatic env.
  • ConfigNoEnv() — disable env handling.
  • ConfigDefault(key string, value any) — set default.
  • ConfigWithViper(fn func(*viper.Viper) error) — customize viper instance.
  • ConfigWatch(opts ...ConfigWatchOption) — watch config changes.
  • ConfigWatchDebounce(d time.Duration) — debounce watch events.
  • ConfigWatchKeys(keys ...string) — watch specific keys.
  • ConfigDisableWatch() — disable watching for a scope.

=== Diagnostics ===

  • Diagnostics() — enable source-aware diagnostics.

=== Utilities ===

  • ConvertAnys(nodes []Node) — convert a list of nodes into []any.

=== Exported Types ===

  • Node — interface implemented by all nodes.
  • Option — interface for provider/invoke options.
  • ConfigWatchOption — interface for config watch options.

== Examples ==

Look in di/examples for runnable programs:

  • basic
  • module, module2
  • replace, replace2
  • decorate
  • if, switch
  • plan
  • populate
  • auto_group
  • diagnostics*
  • config_*
go run ./di/examples/basic/main.go

Documentation

Overview

Package di provides a small declarative layer on top of Fx for building apps.

The package models apps as nodes (Provide, Invoke, Module, etc.) that can be composed, planned, and built into Fx options. It also includes helpers for:

  • conditional wiring (If/When/Switch)
  • replacements/defaults
  • configuration loading (Viper)
  • diagnostics and lifecycle hooks
  • auto-grouping of providers

See the examples directory for usage patterns.

Index

Constants

View Source
const MetadataGroupName = "di:metadata"

MetadataGroupName is the group tag for metadata entries.

Variables

This section is empty.

Functions

func App

func App(nodes ...any) *appNode

App collects declarative nodes and builds them into an fx.Option.

func Case

func Case(cond bool, nodes ...any) caseNode

Case defines a boolean case for Switch.

func ConfigAutomaticEnv

func ConfigAutomaticEnv() configOption

ConfigAutomaticEnv enables viper.AutomaticEnv.

func ConfigDefault

func ConfigDefault(key string, value any) configOption

ConfigDefault sets a default value.

func ConfigEnvKeyReplacer

func ConfigEnvKeyReplacer(replacer *strings.Replacer) configOption

ConfigEnvKeyReplacer sets the environment key replacer.

func ConfigEnvOverride

func ConfigEnvOverride(prefix ...string) configOption

ConfigEnvOverride enables env overrides using an optional prefix and a dot-to-underscore replacer.

func ConfigEnvPrefix

func ConfigEnvPrefix(prefix string) configOption

ConfigEnvPrefix sets the environment prefix.

func ConfigName

func ConfigName(name string) configOption

ConfigName sets the config name for Viper to search for.

func ConfigNoEnv

func ConfigNoEnv() configOption

ConfigNoEnv disables env overrides for this config.

func ConfigOptional

func ConfigOptional() configOption

ConfigOptional allows missing config files without failing.

func ConfigPath

func ConfigPath(path string) configOption

ConfigPath adds a search path for ConfigName.

func ConfigType

func ConfigType(kind string) configOption

ConfigType sets the config type (e.g. "toml").

func ConfigWithViper

func ConfigWithViper(fn func(*viper.Viper) error) configOption

ConfigWithViper allows custom viper configuration.

func ConvertAnys

func ConvertAnys(nodes []Node) []any

func DefaultCase

func DefaultCase(nodes ...any) switchDefaultNode

DefaultCase defines the default branch for Switch.

func OrderIndex added in v1.1.1

func OrderIndex(value any) (int, bool)

OrderIndex returns the auto-group order index if present.

func Plan

func Plan(nodes ...any) (string, error)

Plan builds the app graph and returns a readable plan.

func PriorityIndex added in v1.1.1

func PriorityIndex(value any) (int, bool)

PriorityIndex returns the priority order index if present.

func ReflectMetadata

func ReflectMetadata[T any](value any) (T, bool)

ReflectMetadata returns metadata for a provided value cast to T, if registered.

func ReflectMetadataAny

func ReflectMetadataAny(value any) (any, bool)

ReflectMetadataAny returns metadata for a provided value, if registered.

func RegisterMetadata

func RegisterMetadata(value any, metadata ...any)

RegisterMetadata attaches metadata to an instance programmatically. Note: only pointer-like values can be registered (same as ReflectMetadata).

func Run

func Run(nodes ...any) error

Run builds and runs the app, restarting on config changes.

func WhenCase

func WhenCase(fn any, nodes ...any) caseNode

WhenCase defines a predicate case for Switch. The function may be func() bool or func(T) bool, where T is resolved from config sources.

Types

type ConfigWatchOption

type ConfigWatchOption interface {
	// contains filtered or unexported methods
}

func ConfigDisableWatch

func ConfigDisableWatch() ConfigWatchOption

ConfigDisableWatch disables watching for this config.

func ConfigWatch

func ConfigWatch(opts ...ConfigWatchOption) ConfigWatchOption

ConfigWatch enables config watching for this config or for the whole app if used at top-level.

func ConfigWatchDebounce

func ConfigWatchDebounce(d time.Duration) ConfigWatchOption

ConfigWatchDebounce sets a debounce duration for config change events.

func ConfigWatchKeys

func ConfigWatchKeys(keys ...string) ConfigWatchOption

ConfigWatchKeys watches only specific keys (e.g. "app", "db.host").

type MetadataValue

type MetadataValue struct {
	Value    any
	Type     reflect.Type
	Name     string
	Group    string
	Metadata any
}

MetadataValue pairs a provided value with its metadata tag.

type MockConfigWatchOption added in v1.2.0

type MockConfigWatchOption struct {
	mock.Mock
}

MockConfigWatchOption is an autogenerated mock type for the ConfigWatchOption type

func NewMockConfigWatchOption added in v1.2.0

func NewMockConfigWatchOption(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockConfigWatchOption

NewMockConfigWatchOption creates a new instance of MockConfigWatchOption. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockConfigWatchOption) EXPECT added in v1.2.0

type MockConfigWatchOption_Expecter added in v1.2.0

type MockConfigWatchOption_Expecter struct {
	// contains filtered or unexported fields
}

type MockConfigWatchOption_applyWatch_Call added in v1.2.0

type MockConfigWatchOption_applyWatch_Call struct {
	*mock.Call
}

MockConfigWatchOption_applyWatch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'applyWatch'

func (*MockConfigWatchOption_applyWatch_Call) Return added in v1.2.0

func (*MockConfigWatchOption_applyWatch_Call) Run added in v1.2.0

func (_c *MockConfigWatchOption_applyWatch_Call) Run(run func(configWatchConfigMoqParam *configWatchConfig)) *MockConfigWatchOption_applyWatch_Call

func (*MockConfigWatchOption_applyWatch_Call) RunAndReturn added in v1.2.0

func (_c *MockConfigWatchOption_applyWatch_Call) RunAndReturn(run func(configWatchConfigMoqParam *configWatchConfig)) *MockConfigWatchOption_applyWatch_Call

type MockNode added in v1.2.0

type MockNode struct {
	mock.Mock
}

MockNode is an autogenerated mock type for the Node type

func NewMockNode added in v1.2.0

func NewMockNode(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockNode

NewMockNode creates a new instance of MockNode. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockNode) Build added in v1.2.0

func (_mock *MockNode) Build() (fx.Option, error)

Build provides a mock function for the type MockNode

func (*MockNode) EXPECT added in v1.2.0

func (_m *MockNode) EXPECT() *MockNode_Expecter

type MockNodeOption added in v1.2.0

type MockNodeOption struct {
	mock.Mock
}

MockNodeOption is an autogenerated mock type for the NodeOption type

func NewMockNodeOption added in v1.2.0

func NewMockNodeOption(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockNodeOption

NewMockNodeOption creates a new instance of MockNodeOption. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockNodeOption) Build added in v1.2.0

func (_mock *MockNodeOption) Build() (fx.Option, error)

Build provides a mock function for the type MockNodeOption

func (*MockNodeOption) EXPECT added in v1.2.0

type MockNodeOption_Build_Call added in v1.2.0

type MockNodeOption_Build_Call struct {
	*mock.Call
}

MockNodeOption_Build_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Build'

func (*MockNodeOption_Build_Call) Return added in v1.2.0

func (*MockNodeOption_Build_Call) Run added in v1.2.0

func (*MockNodeOption_Build_Call) RunAndReturn added in v1.2.0

func (_c *MockNodeOption_Build_Call) RunAndReturn(run func() (fx.Option, error)) *MockNodeOption_Build_Call

type MockNodeOption_Expecter added in v1.2.0

type MockNodeOption_Expecter struct {
	// contains filtered or unexported fields
}

func (*MockNodeOption_Expecter) Build added in v1.2.0

Build is a helper method to define mock.On call

type MockNodeOption_applyBind_Call added in v1.2.0

type MockNodeOption_applyBind_Call struct {
	*mock.Call
}

MockNodeOption_applyBind_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'applyBind'

func (*MockNodeOption_applyBind_Call) Return added in v1.2.0

func (*MockNodeOption_applyBind_Call) Run added in v1.2.0

func (_c *MockNodeOption_applyBind_Call) Run(run func(bindConfigMoqParam *bindConfig)) *MockNodeOption_applyBind_Call

func (*MockNodeOption_applyBind_Call) RunAndReturn added in v1.2.0

func (_c *MockNodeOption_applyBind_Call) RunAndReturn(run func(bindConfigMoqParam *bindConfig)) *MockNodeOption_applyBind_Call

type MockNodeOption_applyParam_Call added in v1.2.0

type MockNodeOption_applyParam_Call struct {
	*mock.Call
}

MockNodeOption_applyParam_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'applyParam'

func (*MockNodeOption_applyParam_Call) Return added in v1.2.0

func (*MockNodeOption_applyParam_Call) Run added in v1.2.0

func (_c *MockNodeOption_applyParam_Call) Run(run func(paramConfigMoqParam *paramConfig)) *MockNodeOption_applyParam_Call

func (*MockNodeOption_applyParam_Call) RunAndReturn added in v1.2.0

func (_c *MockNodeOption_applyParam_Call) RunAndReturn(run func(paramConfigMoqParam *paramConfig)) *MockNodeOption_applyParam_Call

type MockNode_Build_Call added in v1.2.0

type MockNode_Build_Call struct {
	*mock.Call
}

MockNode_Build_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Build'

func (*MockNode_Build_Call) Return added in v1.2.0

func (_c *MockNode_Build_Call) Return(option fx.Option, err error) *MockNode_Build_Call

func (*MockNode_Build_Call) Run added in v1.2.0

func (_c *MockNode_Build_Call) Run(run func()) *MockNode_Build_Call

func (*MockNode_Build_Call) RunAndReturn added in v1.2.0

func (_c *MockNode_Build_Call) RunAndReturn(run func() (fx.Option, error)) *MockNode_Build_Call

type MockNode_Expecter added in v1.2.0

type MockNode_Expecter struct {
	// contains filtered or unexported fields
}

func (*MockNode_Expecter) Build added in v1.2.0

Build is a helper method to define mock.On call

type MockOption added in v1.2.0

type MockOption struct {
	mock.Mock
}

MockOption is an autogenerated mock type for the Option type

func NewMockOption added in v1.2.0

func NewMockOption(t interface {
	mock.TestingT
	Cleanup(func())
}) *MockOption

NewMockOption creates a new instance of MockOption. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. The first argument is typically a *testing.T value.

func (*MockOption) EXPECT added in v1.2.0

func (_m *MockOption) EXPECT() *MockOption_Expecter

type MockOption_Expecter added in v1.2.0

type MockOption_Expecter struct {
	// contains filtered or unexported fields
}

type MockOption_applyBind_Call added in v1.2.0

type MockOption_applyBind_Call struct {
	*mock.Call
}

MockOption_applyBind_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'applyBind'

func (*MockOption_applyBind_Call) Return added in v1.2.0

func (*MockOption_applyBind_Call) Run added in v1.2.0

func (_c *MockOption_applyBind_Call) Run(run func(bindConfigMoqParam *bindConfig)) *MockOption_applyBind_Call

func (*MockOption_applyBind_Call) RunAndReturn added in v1.2.0

func (_c *MockOption_applyBind_Call) RunAndReturn(run func(bindConfigMoqParam *bindConfig)) *MockOption_applyBind_Call

type MockOption_applyParam_Call added in v1.2.0

type MockOption_applyParam_Call struct {
	*mock.Call
}

MockOption_applyParam_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'applyParam'

func (*MockOption_applyParam_Call) Return added in v1.2.0

func (*MockOption_applyParam_Call) Run added in v1.2.0

func (_c *MockOption_applyParam_Call) Run(run func(paramConfigMoqParam *paramConfig)) *MockOption_applyParam_Call

func (*MockOption_applyParam_Call) RunAndReturn added in v1.2.0

func (_c *MockOption_applyParam_Call) RunAndReturn(run func(paramConfigMoqParam *paramConfig)) *MockOption_applyParam_Call

type Node

type Node interface {
	Build() (fx.Option, error)
}

Node is a declarative DI node that can be built into fx.Options.

func AutoGroup

func AutoGroup[T any](group ...string) Node

AutoGroup registers an interface to be auto-grouped within the scope. Default group name is lowercased interface name unless provided.

func AutoInject

func AutoInject() Node

AutoInject enables automatic injection into tagged struct fields. Supported tags:

di:"inject"
di:"name=prod"
di:"group=loggers"
di:"optional"

Tags can be comma-separated.

func Config

func Config[T any](pathOrKey string, opts ...any) Node

Config loads a configuration file or binds a key from a shared ConfigFile. If the first argument looks like a file path, it is treated as a config file path. Otherwise it is treated as a key and requires ConfigFile or Config* options.

func ConfigBind

func ConfigBind[T any](key string, opts ...any) Node

ConfigBind provides a sub-config by key from a shared ConfigFile.

func ConfigFile

func ConfigFile(path string, opts ...any) Node

ConfigFile loads a config file once and exposes it for ConfigBind.

func Decorate

func Decorate(function any, opts ...Option) Node

Decorate declares a decorate node.

func Default

func Default(value any, opts ...any) Node

Default declares a binding used only if no matching Provide/Supply exists.

func Diagnostics

func Diagnostics() Node

Diagnostics installs a minimal error hook.

func If

func If(cond bool, nodes ...any) Node

If conditionally includes nodes based on a boolean.

func Invoke

func Invoke(function any, opts ...Option) Node

Invoke declares an invoke node.

func Module

func Module(name string, nodes ...any) Node

Module declares a named module of nodes.

func OnStart

func OnStart(fn any) Node

OnStart registers a lifecycle OnStart hook.

func OnStop

func OnStop(fn any) Node

OnStop registers a lifecycle OnStop hook.

func Populate

func Populate(args ...any) Node

Populate declares a populate node.

func Provide

func Provide(constructor any, opts ...any) Node

Provide declares a constructor and options; use App(...).Build() to compile.

func Replace

func Replace(value any, opts ...any) Node

Replace declares a replacement value for the entire scope.

func ReplaceAfter

func ReplaceAfter(value any, opts ...any) Node

ReplaceAfter applies only to nodes declared after it in the same scope.

func ReplaceBefore

func ReplaceBefore(value any, opts ...any) Node

ReplaceBefore applies only to nodes declared before it in the same scope.

func Supply

func Supply(value any, opts ...any) Node

Supply declares a value and options; use App(...).Build() to compile.

func Switch

func Switch(items ...any) Node

Switch selects the first matching Case, or Default if none match.

func When

func When(fn any, nodes ...any) Node

When conditionally includes nodes based on a function. The function may be func() bool or func(T) bool, where T is resolved from config sources.

type NodeOption

type NodeOption interface {
	Node
	Option
}

NodeOption is implemented by types that can act as both Node and Option.

func Options

func Options(nodes ...any) NodeOption

Options groups nodes without a name.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is applied to providers and/or invocations.

func As

func As[T any](tags ...string) Option

As exposes the constructor result as type T (non-grouped).

func AsSelf

func AsSelf[T any](tags ...string) Option

AsSelf creates a new Option that provides the given value as a dependency and tags it with the given tags. Example usage:

di.Provide(NewHandler, di.AsSelf[realtime.Authorizer]())),

Equivalent to:

di.Provide(NewHandler, di.As[realtime.Authorizer](), di.Self()),

func AutoGroupAsSelf

func AutoGroupAsSelf() Option

AutoGroupAsSelf ensures the concrete type is provided alongside auto-grouping.

func AutoGroupFilter

func AutoGroupFilter(fn func(reflect.Type) bool) Option

AutoGroupFilter narrows auto grouping to types that pass the predicate.

func AutoGroupIgnore

func AutoGroupIgnore() Option

AutoGroupIgnore disables auto-grouping for this provider.

func AutoGroupIgnoreType

func AutoGroupIgnoreType[T any](group ...string) Option

AutoGroupIgnoreType ignores auto-grouping for the given interface. If a group is provided, it targets that group; otherwise it ignores all groups for the interface.

func AutoInjectIgnore

func AutoInjectIgnore() Option

AutoInjectIgnore disables auto field injection for this provider.

func Group

func Group(name string) Option

Group applies a group tag. For Provide it sets the output group, for Invoke/Decorate it sets the input tag.

func InGroup

func InGroup(name string) Option

InGroup tags the next parameter for a group.

func InTag

func InTag(tag string) Option

InTag appends a param tag in positional order.

func Metadata

func Metadata(value any) Option

Metadata attaches a metadata tag to a provider.

func MetadataGroup

func MetadataGroup() Option

MetadataGroup tags the next parameter to receive metadata entries.

func Name

func Name(name string) Option

Name applies a name tag. For Provide it sets the output name, for Invoke/Decorate it sets the input tag.

func Optional

func Optional() Option

Optional marks the next parameter optional.

func Params

func Params(items ...any) Option

Params scopes options to positional parameter tags only.

func Priority added in v1.1.1

func Priority(value PriorityLevel) Option

Priority overrides the auto-group order for a provided value.

func Private

func Private() Option

Private hides this constructor from other modules.

func Public

func Public() Option

Public clears a previously set Private option.

func Self

func Self() Option

Self exposes the concrete type along with any other As* options.

func ToGroup

func ToGroup(name string) Option

ToGroup assigns the previous As to a group.

type PriorityLevel added in v1.1.1

type PriorityLevel int

PriorityLevel controls auto-group ordering for provided values. Lower values are ordered earlier.

const (
	Earliest PriorityLevel = -10000
	Earlier  PriorityLevel = -5000
	Normal   PriorityLevel = 0
	Later    PriorityLevel = 5000
	Latest   PriorityLevel = 10000
)

func Between added in v1.1.1

func Between(lower, upper PriorityLevel) PriorityLevel

Between returns a PriorityLevel between lower and upper.

Directories

Path Synopsis
_examples
auto_group command
basic command
composit command
config_default command
config_env command
config_json command
config_toml command
config_watch command
config_yaml command
decorate command
diagnostics command
diagnostics_pkg command
diagnostics_zap command
if command
lifecycle command
module command
module2 command
params command
plan command
populate command
replace command
replace2 command
switch command

Jump to

Keyboard shortcuts

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