OKHAM.org Documentation EnglishCastellano

February 2026 edition

Dependency Injection Specification

Disclaimer: This document is non-normative and describes recommended practices for the OKHAM ecosystem.

Version 1.0.0

Status: DRAFT

This document specifies the dependency injection patterns for all OKHAM capabilities.


Golden Rules

1. RuntimeContext is the Primary Injection Point

All capabilities MUST receive dependencies through capabilityruntime.RuntimeContext:

// CORRECT - dependencies come from RuntimeContext
func NewCapability(rt *capabilityruntime.RuntimeContext) *Capability {
    return &Capability{
        rt:   rt,
        nats: rt.NC,
        js:   rt.JS,
    }
}

2. Never Create Dependencies Internally

// FORBIDDEN - creating logger internally
func NewCapability() *Capability {
    logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
    return &Capability{log: logger}
}

// FORBIDDEN - creating NATS connection internally
func NewCapability() *Capability {
    nc, _ := nats.Connect("nats://localhost:4222")
    return &Capability{nc: nc}
}

3. Accept Interfaces, Return Structs

// CORRECT - handler accepts interface
type MessageHandler interface {
    Handle(msg *nats.Msg) error
}

func NewProcessor(handler MessageHandler) *Processor {
    return &Processor{handler: handler}
}

Standard Dependencies via RuntimeContext

Dependency Access Type
Logger rt.Logger logger.Logger
NATS Connection rt.NC *nats.Conn
JetStream rt.JS nats.JetStreamContext
HTTPBasePath rt.HTTPBasePath string
FieldBuilder rt.F FieldBuilder

Optional Dependencies Pattern

For optional features, use functional options:

type Option func(*Capability)

func WithCustomClient(client *http.Client) Option {
    return func(c *Capability) {
        c.httpClient = client
    }
}

func NewCapability(rt *capabilityruntime.RuntimeContext, opts ...Option) *Capability {
    c := &Capability{
        rt:        rt,
        httpClient: http.DefaultClient, // default
    }
    for _, opt := range opts {
        opt(c)
    }
    return c
}

Testing Benefits

Proper DI enables easy testing:

func TestCapability(t *testing.T) {
    // Create mock runtime context
    mockRT := &capabilityruntime.RuntimeContext{
        Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
        NC:     testNATSConn,
    }

    cap := NewCapability(mockRT)
    // Test with injected mocks...
}

Global State is Forbidden

// FORBIDDEN - package-level variables
var (
    globalLogger *slog.Logger
    globalNATS   *nats.Conn
)

// FORBIDDEN - init() for dependencies
func init() {
    globalLogger = slog.Default()
}