Skip to content

dix examples

dix Examples

This page collects the runnable examples/dix programs and maps them to the API surface they demonstrate.

Run Locally

Run from the examples/dix module:

cd examples/dix
go run ./basic
go run ./runtime_scope
go run ./inspect

Core Examples

ExampleFocusDirectory
basicimmutable app spec, build/start/stop, health checks, logx integrationexamples/dix/basic
aggregate_paramsprovider graph composition with multiple typed dependenciesexamples/dix/aggregate_params
build_runtimeexplicit Build() to Runtime flowexamples/dix/build_runtime
build_failurevalidation/build failure behaviorexamples/dix/build_failure

Advanced Examples

ExampleFocusDirectory
advanced_do_bridgeexplicit do bridge setupexamples/dix/advanced_do_bridge
named_aliasnamed services and typed alias bindingexamples/dix/named_alias
runtime_scoperequest-like runtime scope and scoped providersexamples/dix/runtime_scope
transienttransient provider semanticsexamples/dix/transient
overridestructured overridesexamples/dix/override
inspectruntime inspection and diagnosticsexamples/dix/inspect

Example: Basic App Composition

app := dix.New(
    "basic",
    dix.WithLogger(logger),
    dix.WithModule(
        dix.NewModule("config",
            dix.WithModuleProviders(
                dix.Provider0(func() Config { return Config{Port: 8080} }),
            ),
        ),
    ),
)

if err := app.Validate(); err != nil {
    panic(err)
}

rt, err := app.Build()
if err != nil {
    panic(err)
}
defer func() {
    _, _ = rt.StopWithReport(context.Background())
}()

if err := rt.Start(context.Background()); err != nil {
    panic(err)
}

Example: Runtime Scope

requestScope := advanced.Scope(rt, "request-42", func(injector do.Injector) {
    advanced.ProvideScopedValue(injector, RequestContext{RequestID: "req-42"})
    advanced.ProvideScoped2(injector, func(cfg AppConfig, req RequestContext) ScopedService {
        return ScopedService{Config: cfg, Request: req}
    })
})

svc, err := advanced.ResolveScopedAs[ScopedService](requestScope)
if err != nil {
    panic(err)
}
fmt.Println(svc.Request.RequestID)

Example: Fine-Grained Inspection

provided := advanced.ListProvidedServices(rt)
deps := advanced.ExplainNamedDependencies(rt, "tenant.default")

fmt.Println("provided services:", len(provided))
fmt.Println("tenant graph known:", deps["tenant.default"] != "")

Use the fine-grained inspection helpers when you only need one diagnostic view. InspectRuntime(...) remains convenient, but it is the heavier aggregation path.