assemble

package module
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2025 License: MIT Imports: 8 Imported by: 0

README

assemble — Pragmatic Dependency Injection for Go

assemble is a pragmatic, lightweight dependency injection (DI) library for Go.
It focuses on clarity, type safety, and zero reflection through a combination of runtime and generated dependency graphs.

Go Build Go Lint

Key Features

  • 🧩 Strongly typed DI container — safe, reflection-free dependency resolution
  • ⚙️ Static code generation: compile-time wiring for performance and safety
  • 🔄 Lifecycle hooks: OnStart, OnStop, plus type-aware OnStartFor[T] / OnStopFor[T]
  • 🧠 Deterministic startup and shutdown based on creation order and priorities
  • ⏱️ Timeouts and multi-error aggregation for clean lifecycle management
  • 🧭 Graph export (DOT / PlantUML) for visualizing dependency and shutdown order
  • 🧰 Designed for modular services, CLIs, and testable applications

Installation

To use and import the library, run:

go get github.com/xfrr/assemble

To install the generator tool, run:

go install github.com/xfrr/assemble/cmd/assemblegen@latest

Usage

Check the example for a complete usage demonstration.

License

MIT License. See LICENSE for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrBindingNotFound = errors.New("binding not found")
	ErrInvokeFail      = errors.New("invoke failed")
)

Functions

func Get

func Get[T any](ctx context.Context, r Resolver, opts ...KeyOpt) (T, error)

Get resolves a dependency of type T from the Resolver r. When called with no KeyOpt, it uses a zero-alloc fast path. If options are provided, it falls back to building a keyed lookup once.

func GetByKey

func GetByKey[T any](ctx context.Context, r Resolver, k Key) (T, error)

GetByKey resolves a dependency using a precomputed key (no per-call key building). This is the preferred path for generated code and other hot code paths.

Types

type Appender

type Appender[T any] struct {
	// contains filtered or unexported fields
}

func Append

func Append[T any](p Provider[T], opts ...RegOpt) Appender[T]

Append adds an appender to a multi-binding set for T.

type AsOpt

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

AsOpt encodes a "bind interface to implementation type" choice.

func As

func As[T any]() AsOpt

As specifies the interface type to bind to.

type BadCastError

type BadCastError struct {
	Key  Key
	From reflect.Type
	To   reflect.Type
}

func (BadCastError) Error

func (e BadCastError) Error() string

type BindError

type BindError struct {
	From reflect.Type
	To   reflect.Type
	Why  string
}

func (BindError) Error

func (e BindError) Error() string

type Container

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

Container is the runtime DI container built from Modules.

func Assemble

func Assemble(ms ...Module) (*Container, error)

Assemble builds a Container from the provided Module(s).

func (*Container) ExportCreationOrderDOT

func (c *Container) ExportCreationOrderDOT() string

ExportCreationOrderDOT returns a DOT graph (Graphviz) of the creation order. Rank is left-to-right; edges connect creation sequence.

func (*Container) ExportCreationOrderPlantUML

func (c *Container) ExportCreationOrderPlantUML() string

ExportCreationOrderPlantUML returns a simple PlantUML activity diagram of creation order.

func (*Container) Shutdown

func (c *Container) Shutdown(ctx context.Context) error

Shutdown runs Stop(ctx) and returns a formatted error tree (if any).

func (*Container) Start

func (c *Container) Start(ctx context.Context) error

Start runs all OnStart/Invoke hooks with timeout & multi-error aggregation.

func (*Container) Stop

func (c *Container) Stop(ctx context.Context) error

Stop runs all OnStop hooks honoring priority and registration/creation order.

type HookOpt

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

func WithPriority

func WithPriority(p int) HookOpt

WithPriority assigns a group/priority:

Start: lower values start earlier
Stop:  higher values stop later (reverse order)

func WithStartTimeout

func WithStartTimeout(d time.Duration) HookOpt

WithStartTimeout sets a per-hook timeout applied by Container.Start.

func WithStopTimeout

func WithStopTimeout(d time.Duration) HookOpt

WithStopTimeout sets a per-hook timeout applied by Container.Stop.

type Key

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

Key identifies a dependency by type (and optional name). If typ is a slice, sliceElem holds its element type to speed up set handling.

func KeyOf

func KeyOf[T any]() Key

KeyOf returns a precomputed key for T with no name. Use this in hot paths or generated code to avoid per-call option handling.

func NamedKey

func NamedKey[T any](name string) Key

NamedKey returns a precomputed key for T with the given name. Name application is done once here, not on every Get call.

type KeyOpt

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

KeyOpt modifies the key used to look up a dependency.

func WithName

func WithName(name string) KeyOpt

WithName specifies a name for the dependency to look up.

type Module

type Module []Registrar

Module groups related registrations.

func Modules

func Modules(ms ...Module) Module

Modules flattens multiple modules into one.

type MultiError

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

MultiError aggregates multiple errors into one.

func IsMultiError

func IsMultiError(err error) (*MultiError, bool)

IsMultiError returns true if the error is a MultiError. It uses errors.As to unwrap the error chain.

func (*MultiError) Append

func (m *MultiError) Append(err error)

func (*MultiError) Error

func (m *MultiError) Error() string

func (*MultiError) Len

func (m *MultiError) Len() int

func (*MultiError) TreeString

func (m *MultiError) TreeString(indent string) string

TreeString renders a simple indented list of aggregated errors.

func (*MultiError) Unwrap

func (m *MultiError) Unwrap() []error

type NotFoundError

type NotFoundError struct {
	Type reflect.Type
	Name string
}

func (NotFoundError) Error

func (e NotFoundError) Error() string

type Provider

type Provider[T any] func(ctx context.Context, r Resolver) (T, error)

Provider is a constructor that can resolve its dependencies via Resolve.

type RegOpt

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

RegOpt modifies registration behavior.

func Name

func Name(name string) RegOpt

Name specifies a name for the registration.

type Registrar

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

Registrar mutates a module (registers providers, binds, etc.).

func Bind

func Bind[I any](as AsOpt, opts ...RegOpt) Registrar

Bind declares an interface binding to a concrete implementation.

func Invoke

func Invoke(fn func(ctx context.Context, r Resolver) error) Registrar

Invoke registers a startup hook. The function may resolve deps via Resolve.

func OnStart

func OnStart(fn func(ctx context.Context, r Resolver) error, opts ...HookOpt) Registrar

OnStart registers a startup hook executed by Container.Start(ctx). Ordering: priority ASC, then registration/order ASC.

func OnStartFor

func OnStartFor[T any](fn func(ctx context.Context, r Resolver, t T) error, opts ...HookOpt) Registrar

OnStartFor resolves T and passes it to the hook; useful to pre-warm or ping services.

func OnStop

func OnStop(fn func(ctx context.Context, r Resolver) error, opts ...HookOpt) Registrar

OnStop registers a shutdown hook executed by Container.Stop(ctx). Ordering: priority DESC, then registration/order DESC (reverse).

func OnStopFor

func OnStopFor[T any](fn func(ctx context.Context, r Resolver, t T) error, opts ...HookOpt) Registrar

OnStopFor registers a shutdown hook tied to a specific type T. The hook runs after dependents of T, by ordering using T's creation index (instances created later stop earlier).

func Provide

func Provide[T any](p Provider[T], opts ...RegOpt) Registrar

Provide registers a provider of a concrete type T (usually a singleton).

func Set

func Set[T any](appenders ...Appender[T]) Registrar

Set registers a multi-binding set for T, returned as []T on Get[[]T].

type Resolver

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

Resolver resolves dependencies.

Directories

Path Synopsis
cmd
assemble command
di
Code generated by github.com/xfrr/assemble; DO NOT EDIT.
Code generated by github.com/xfrr/assemble; DO NOT EDIT.
internal
Code generated by github.com/xfrr/assemble; DO NOT EDIT.
Code generated by github.com/xfrr/assemble; DO NOT EDIT.

Jump to

Keyboard shortcuts

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