Awesome Go

floatdrop/di

CategoryMiscellaneous
SubcategoryDependency Injection
Stars15

Dependency injection container built on generic methods, with child scopes, lifecycle hooks and graph validation before anything is built

About floatdrop/di

di

CI Go Reference coverage License: MIT Awesome Go

A dependency-injection container for Go 1.27+. Constructors are plain functions, keys are Go types, and services are built, started and stopped in dependency order. No code generation or dependencies outside the standard library.

Installation

go get golang.yandex/di

Requires Go 1.27 or newer. Editor support for generic methods needs gopls v0.23 or newer.

Quick start

A complete program using stand-in database and server types:

// Quick start: register a few services, start and stop the application.
package main

import (
	"context"
	"fmt"
	"log"

	"golang.yandex/di"
)

type Config struct{ DSN string }
type DB struct{ dsn string }
type Repo struct{ db *DB }
type Server struct{ repo *Repo }

// Plain constructors: their parameters are their dependencies.
func NewDB(cfg Config) *DB         { return &DB{dsn: cfg.DSN} }
func NewRepo(db *DB) *Repo         { return &Repo{db: db} }
func NewServer(repo *Repo) *Server { return &Server{repo: repo} }

func main() {
	app := di.New()

	app.Value(Config{DSN: "postgres://localhost/app"})

	app.Wire[*DB](NewDB).
		OnStop(func(ctx context.Context, db *DB) error { fmt.Println("db closed"); return nil })

	app.Wire[*Repo](NewRepo)

	app.Wire[*Server](NewServer).
		Eager().
		OnStart(func(ctx context.Context, srv *Server) error { fmt.Println("listening"); return nil }).
		OnStop(func(ctx context.Context, srv *Server) error { fmt.Println("server stopped"); return nil })

	ctx := context.Background()
	if err := app.Start(ctx); err != nil {
		log.Fatal(err)
	}
	defer func() {
		if err := app.Stop(ctx); err != nil {
			log.Println(err)
		}
	}()

	fmt.Println("serving", app.Get[*Server]().repo.db.dsn)
}

Value registers an existing value; Wire registers a constructor whose parameters are its dependencies. Registrations are lazy singletons by default. Eager() builds the server during Start, resolving its dependencies first. Stop runs the stop hooks in reverse build order: server before database.

The source is examples/quickstart/main.go. For a long-running application, Run starts, waits for a signal or shutdown request, then stops with a deadline; see the HTTP server.

Capabilities

API
RegistrationPlain constructors with Wire, scope-aware closures with Provide, existing values with Value.
ScopesShared singletons or one instance per resolving scope with Scoped().
LifecycleStart, drain and stop hooks; background workers; signal handling with Run.
Optional dependencies and groupsDeclare optional parameters and group slices with Needs.
Modules and wrappersCompose registration functions with Use; decorate services with Wrap.
TestingFresh scopes with di.Test and explicit Override() registrations.
Validation and inspectionCheck declared dependencies before construction; render dependency trees, Graphviz DOT and module reports.
HTTP and gRPCRequest scopes, handler resolution and server lifecycle with dihttp and digrpc.
ObservabilityConstructor and hook events with Observe; log/slog integration with dislog.

Wire reads constructor signatures once with reflection, so Validate can check their dependencies without building anything. Provide closures are checked only when they run and are reported as unchecked by Validate.

Documentation

Performance

The benchmarks/ module compares the same four-service graph on an Apple M3 Max:

Warm resolveCold register and build
di, Provide closure21 ns, 0 B, 0 allocs4.0 µs, 4.4 kB, 68 allocs
di, Wire21 ns, 0 B, 0 allocs5.1 µs, 5.4 kB, 86 allocs
do v2.1134 ns, 160 B, 6 allocs7.0 µs, 11.2 kB, 120 allocs
dig v1.19486 ns, 768 B, 24 allocs19.9 µs, 24.3 kB, 302 allocs

The dig warm figure measures reflective Invoke, not a typed accessor. An fx application normally invokes once at startup; the cold comparison is the fairer one.

cd benchmarks && go test -bench . -benchmem

Versioning

While the major version is 0, a minor bump may change behaviour. CHANGELOG.md and the releases state whether an upgrade can break a caller.

Contributing

See CONTRIBUTING.md for the CLA, tests and example-sync instructions.

License

MIT

Frequently Asked Questions

What is floatdrop/di?

floatdrop/di is a Miscellaneous library for the Go programming language. Dependency injection container built on generic methods, with child scopes, lifecycle hooks and graph validation before anything is built

How do I install floatdrop/di?

Install floatdrop/di with the Go module system using `go get floatdrop/di`. Check the repository for the current installation instructions.

What category does floatdrop/di belong to?

floatdrop/di is listed under Miscellaneous, specifically Dependency Injection.

← Back to Dependency Injection