Thanks to visit codestin.com
Credit goes to github.com

Skip to content

eerzho/simpledi

Repository files navigation

simpledi

Release License Go Reference Go Report Codecov

A simple dependency injection container for Go.

Zero dependencies, no reflection, no code generation.

Install

go get github.com/eerzho/simpledi

Example

package main

import "github.com/eerzho/simpledi"

type Database struct {
	URL string
}

func (d *Database) Close() error {
	return errors.New("database close error")
}

type Service struct {
	Database *Database
}

func main() {
	// Close all definitions in reverse order at the end
	defer simpledi.Close()

	// Define database
	simpledi.Set(simpledi.Definition{
		ID:   "database",
		New: func() any {
			return &Database{URL: "postgres"}
		},
		Close: func() error {
			database := simpledi.Get[*Database]("database")
			return database.Close()
		},
	})

	// Define service
	simpledi.Set(simpledi.Definition{
		ID:   "service",
		Deps: []string{"database"},
		New: func() any {
			database := simpledi.Get[*Database]("database")
			return &Service{Database: database}
		},
	})

	// Resolve all dependencies in correct order
	simpledi.Resolve()

	// Use the service
	service := simpledi.Get[*Service]("service")
	_ = service
}

Features

  • Zero dependencies
  • No reflection
  • Type-safe with generics
  • Automatic dependency ordering

Docs

Full documentation and examples: pkg.go.dev.

Current state

simpledi provides the core features intended.

Further improvements or new features may be introduced as good ideas come up.

Suggestions and feedback are always welcome.

Star History

Star History Chart

About

DI container, MIT license

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published