Skip to content

Dependency Injection (core/di) ​

GoForge includes a pure-Go reflection DI container (github.com/mmycin/goforge/core/di) with zero external runtime DI dependencies. boot re-exports boot.Module = di.Module and boot.Bind[I] for convenience.


Core Concepts & API ​

di.Module ​

A module groups providers, invoke hooks, GORM models, and optional nested submodules:

go
type Module struct {
	Name      string
	Providers []any    // Constructors or di.Binding values
	Invokes   []any    // Startup callbacks (e.g. RegisterListeners)
	Models    []any    // GORM model pointers (&Todo{}, &User{})
	Modules   []Module // Nested submodules
}

Container Construction & Options ​

go
c := di.New(
	di.AutoCollect[server.Router](),
	di.AutoCollect[server.GRPCRegistry](),
	di.WithProviders(NewConfig, NewDB),
	di.WithModules(auth.Module(), task.Module()),
	di.WithInvokes(func(bus *events.EventBus) { ... }),
)
Function / MethodSignature / Purpose
di.New(opts ...Option) *ContainerCreates a new container with Lifecycle pre-registered.
di.WithModules(modules ...Module) OptionRegisters modules recursively.
di.WithProviders(providers ...any) OptionRegisters top-level providers.
di.WithInvokes(invokes ...any) OptionRegisters top-level invoke callbacks.
di.AutoCollect[I any]() OptionCollects every provided value implementing interface I into []I in deterministic (Module, Provider) order. Panics at setup if I is not an interface.
di.Bind[I any](constructor any) BindingExposes the return value only as interface I (concrete type must implement I).
di.BindBoth[I any](constructor any) BindingExposes both interface I and the concrete return type pointing to the same singleton instance.
di.CollectModels(modules ...Module) []anyRecursively aggregates Models in declaration order, deduplicated by reflect.Type.
(*Container).Validate() errorValidates the dependency graph statically without calling any constructor.
(*Container).Build() errorIdempotent. Validates graph, instantiates providers topologically, populates AutoCollect slices, runs Invokes. On failure, runs already-registered OnStop hooks to prevent leaks.
(*Container).Start(ctx context.Context) errorBuilds if unbuilt, runs OnStart hooks in registration order. If hook i fails, rolls back hooks 0..i-1 in reverse order.
(*Container).Stop(ctx context.Context) errorRuns all OnStop hooks in LIFO order, clears stopped hooks (idempotent), joins errors via errors.Join.
(*Container).Models() []anyReturns deduplicated models from all registered modules.
di.Resolve[T any](c *Container) (T, error)Resolves a registered type from a built container.
di.Collect[I any](c *Container) []IReturns the auto-collected slice for interface I.

Provider & Invoke Rules ​

  • Providers must be non-variadic functions returning T or (T, error) where T != error.
  • Duplicate providers for the same concrete or bound interface type fail with ErrDuplicateProvider.
  • Invokes must be non-variadic functions returning nothing or error.
  • Cycle detection runs a 3-color DFS during Validate() / Build(), producing a minimal cycle trace (A -> B -> A).

di.Lifecycle ​

di.Lifecycle is automatically available to any provider or invoke function:

go
type Lifecycle interface {
	Append(Hook)
	OnStart(func(context.Context) error)
	OnStop(func(context.Context) error)
}

Example:

go
func NewCache(lc di.Lifecycle) *Cache {
	c := &Cache{}
	lc.OnStart(func(ctx context.Context) error { return c.Connect(ctx) })
	lc.OnStop(func(ctx context.Context) error { return c.Close(ctx) })
	return c
}

Error Kinds ​

All container errors are returned as *di.Error (Error(), Unwrap()) with a Kind field:

ErrorKindMeaning
ErrInvalidSignatureNon-function, variadic function, or invalid return types
ErrMissingDependencyRequired parameter type has no provider
ErrCircularDepCycle detected in dependency graph
ErrDuplicateProviderTwo providers register the same output type
ErrInitFailedA provider constructor or invoke returned an error
ErrResolveFailedResolve[T] called before Build() or for an unregistered type

boot Integration ​

In boot/kernel.go:

  • boot.New(modules ...Module) (*App, error) — loads config via config.Load() and boots the app.
  • boot.NewWithConfig(cfg *config.AllConfig, modules ...Module) (*App, error) — uses an explicit *config.AllConfig (ideal for tests and custom entrypoints).
  • Legacy shims boot.NewApp(...) and boot.NewAppWithServices(...) remain for backwards compatibility, but New / NewWithConfig are preferred for all new code.

Released under the Apache-2.0 License.