Skip to content

Dependency Injection

cmdguard integrates samber/do/v2 for dependency injection. Every CLI owns a scope. Register services on it and invoke them in handlers; there is no global container and no manual wiring.

NewCLI creates the root scope and registers the resolved config as *T, so a provider can depend on the config without extra plumbing. cli.Scope() returns the typed wrapper and cli.Injector() the underlying do.Injector, which is the escape hatch for samber/do calls that cmdguard does not wrap.

Providers are lazy: the function runs on the first Invoke of that type, never at registration.

package main
import (
"context"
"fmt"
"log"
"github.com/larsartmann/cmdguard/v5/pkg/cmdguard/v5"
"github.com/samber/do/v2"
)
type AppConfig struct {
DSN string `flag:"dsn" env:"APP_DSN" default:"postgres://localhost/app" help:"Database DSN"`
}
type Database struct{ dsn string }
func (db *Database) HealthCheck(_ context.Context) error { return nil }
func (db *Database) Shutdown() error { return nil }
func main() {
cli, err := v5.NewCLI[AppConfig]("app", "DI example", AppConfig{})
if err != nil {
log.Fatal(err)
}
err = v5.Provide(cli.Scope(), func(_ do.Injector) (*Database, error) {
cfg, err := v5.Invoke[*AppConfig](cli.Scope())
if err != nil {
return nil, err
}
return &Database{dsn: cfg.DSN}, nil
})
if err != nil {
log.Fatal(err)
}
b := v5.NewBuilder(cli)
v5.Add(b, "info", v5.NoFlags{},
func(_ context.Context, _ *AppConfig, _ v5.NoFlags) error {
db, err := v5.Invoke[*Database](cli.Scope())
if err != nil {
return err
}
fmt.Println("dsn:", db.dsn)
return nil
},
v5.WithShort("Show the resolved database DSN"),
v5.WithNoArgs(),
)
if err := b.Build(); err != nil {
log.Fatal(err)
}
cli.ExecuteAndExit(context.Background())
}
Helper Purpose
Provide[T] Lazy typed provider: func(do.Injector) (T, error)
ProvideNamed[T] Same, registered under a name for multiple implementations
ProvideValue[T] Register an already-constructed value
Invoke[T] Resolve the type, constructing it on first use
InvokeNamed[T] Resolve a named registration

Registration is panic-free: a duplicate registration comes back as an error wrapping ErrServiceRegistration instead of a panic.

Handlers receive the resolved config as *T, so most commands read config directly and invoke only the services they need. Invoke puts ErrServiceNotFound in the error chain when the type was never registered, which is testable with errors.Is. For raw cobra subcommands mixed into the tree, cmdguard.ConfigFromContext[T](ctx) returns the resolved config without an Invoke.

Two method sets are recognized automatically: HealthCheck() error or HealthCheck(context.Context) error for health, and Shutdown() error for teardown.

Health checks surface in two places. The auto-registered doctor command runs every service’s check plus custom checks, and the programmatic API mirrors it:

err := cli.HealthCheck(ctx) // first failing check, or nil
results := cli.HealthCheckResults() // map[string]error
ctxResults := cli.HealthCheckResultsWithContext(ctx) // context-aware variant

Graceful shutdown is ON by default in v5. On SIGINT or SIGTERM, cmdguard cancels the context and then shuts down every instantiated service in dependency-aware order: a service that nothing depends on is closed first, so dependents stop before their dependencies. A normally completing Execute never tears the scope down, which keeps repeated ExecuteWithArgs runs safe. For explicit teardown call cli.Shutdown(ctx). WithoutGracefulShutdown() keeps signal handling but skips DI shutdown; WithoutSignalHandling() disables both.

Clone the scope, then override. Clone copies the registrations but not the instantiated state:

func TestInfo(t *testing.T) {
cloned := v5.CloneScope(cli.Scope())
if err := v5.OverrideValue(cloned, &Database{dsn: "test://mock"}); err != nil {
t.Fatal(err)
}
if _, err := v5.Invoke[*Database](cloned); err != nil {
t.Fatal(err)
}
}

Override[T](scope, fn) replaces a provider and OverrideValue[T](scope, v) replaces it with a value. Both return an error only for a nil scope.

A scope can be built before the CLI and handed over with WithCLIScope:

scope := v5.NewScopeWithOpts("app", &do.InjectorOpts{
Logf: func(format string, args ...any) { log.Printf("DI: "+format, args...) },
})
cli, err := v5.NewCLI[AppConfig]("app", "My app", AppConfig{},
v5.WithCLIScope(scope),
)

NewScope(name) makes a plain scope, NewScopeFromInjector(injector, name) adopts an existing do.Injector, and v5.Package(scope, name, short, defaults) binds a new CLI to a scope and registers the CLI itself in that scope. Child scopes isolate plugins and subsystems:

child, err := v5.RegisterInScope(cli.Scope(), "workers",
func(_ do.Injector) (*WorkerPool, error) { return NewWorkerPool(), nil })
wrapped := v5.ScopedProvider(cli.Scope(), "reports", func(i do.Injector) (*ReportStore, error) {
return NewReportStore(i), nil
})

RegisterInScope creates the child scope and registers one typed provider under its own type key; ScopedProvider wraps a provider so it resolves inside a named child scope. To trace service construction and shutdown, pass WithDILogging(logf) to NewCLI; the injector’s internal log lines then go to your logger.