container

package
v0.0.2-alpha Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package container provides a type-safe IoC dependency injection container.

A Container holds named bindings — factory functions that produce values on demand. Bindings are either transient (a fresh value per resolution) or singleton (a single value cached after the first successful resolution).

The zero value of Container is not usable; call New.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Make

func Make[T any](c resolver, name string) (T, error)

Make resolves a binding by name and type-asserts the result to T. Returns an error if the binding is missing, the factory fails, or the produced value is not assignable to T.

func Must

func Must[T any](c resolver, name string) T

Must resolves a binding by name and type-asserts the result to T. It panics if the binding is missing, the factory fails, or the type does not match. Prefer Make in code that needs to handle errors gracefully; Must is intended for startup paths where a missing dependency is fatal by definition.

Types

type Container

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

Container is an IoC dependency injection container. It is safe for concurrent use.

func New

func New() *Container

New returns an empty Container ready to accept bindings.

func (*Container) Bind

func (c *Container) Bind(name string, fn Factory)

Bind registers a transient factory under name. Each call to Make invokes the factory again. If name is already bound, the previous binding is replaced.

func (*Container) Count

func (c *Container) Count() int

Count returns the number of registered bindings.

func (*Container) Has

func (c *Container) Has(name string) bool

Has reports whether a binding with the given name is registered.

func (*Container) List

func (c *Container) List() []string

List returns the names of all registered bindings in alphabetical order.

func (*Container) Make

func (c *Container) Make(name string) (any, error)

Make resolves the binding named name and returns the produced value. Returns an error if the binding is not registered, the factory fails, or a cyclic resolution is detected.

func (*Container) Singleton

func (c *Container) Singleton(name string, fn Factory)

Singleton registers a factory under name that runs at most once. The returned value (or error) is cached and reused on every subsequent Make. Re-registering with Singleton or Bind clears the cached instance.

type Factory

type Factory func(*Container) (any, error)

Factory produces a value from a Container. It runs at resolution time and may fetch or construct dependencies from the same container.

Jump to

Keyboard shortcuts

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