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 / Method | Signature / Purpose |
|---|---|
di.New(opts ...Option) *Container | Creates a new container with Lifecycle pre-registered. |
di.WithModules(modules ...Module) Option | Registers modules recursively. |
di.WithProviders(providers ...any) Option | Registers top-level providers. |
di.WithInvokes(invokes ...any) Option | Registers top-level invoke callbacks. |
di.AutoCollect[I any]() Option | Collects 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) Binding | Exposes the return value only as interface I (concrete type must implement I). |
di.BindBoth[I any](constructor any) Binding | Exposes both interface I and the concrete return type pointing to the same singleton instance. |
di.CollectModels(modules ...Module) []any | Recursively aggregates Models in declaration order, deduplicated by reflect.Type. |
(*Container).Validate() error | Validates the dependency graph statically without calling any constructor. |
(*Container).Build() error | Idempotent. 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) error | Builds 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) error | Runs all OnStop hooks in LIFO order, clears stopped hooks (idempotent), joins errors via errors.Join. |
(*Container).Models() []any | Returns 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) []I | Returns the auto-collected slice for interface I. |
Provider & Invoke Rules
- Providers must be non-variadic functions returning
Tor(T, error)whereT != 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:
ErrorKind | Meaning |
|---|---|
ErrInvalidSignature | Non-function, variadic function, or invalid return types |
ErrMissingDependency | Required parameter type has no provider |
ErrCircularDep | Cycle detected in dependency graph |
ErrDuplicateProvider | Two providers register the same output type |
ErrInitFailed | A provider constructor or invoke returned an error |
ErrResolveFailed | Resolve[T] called before Build() or for an unregistered type |
boot Integration
In boot/kernel.go:
boot.New(modules ...Module) (*App, error)— loads config viaconfig.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(...)andboot.NewAppWithServices(...)remain for backwards compatibility, butNew/NewWithConfigare preferred for all new code.
