/di

🛠 A full-featured dependency injection container for go programming language.

Primary LanguageGoMIT LicenseMIT

DI

Documentation Release Build Status Go Report Card Code Coverage

Dependency injection for Go programming language.

Tutorial | Examples | Advanced features

Dependency injection is one form of the broader technique of inversion of control. It is used to increase modularity of the program and make it extensible.

This library helps you to organize responsibilities in your codebase and make it easy to combine low-level implementation into high-level behavior without boilerplate.

Features

  • Intuitive auto wiring
  • Interface implementations
  • Constructor injection
  • Optional injection
  • Field injection
  • Lazy-loading
  • Tagging
  • Grouping
  • Cleanup
  • Container Chaining / Scopes

Documentation

You can use standard pkg.go.dev and inline code comments. If you do not have experience with auto-wiring libraries as google/wire, uber-go/dig or another - start with tutorial.

Install

go get github.com/goava/di

What it looks like

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"github.com/goava/di"
)

func main() {
	di.SetTracer(&di.StdTracer{})
	// create container
	c, err := di.New(
		di.Provide(NewContext),  // provide application context
		di.Provide(NewServer),   // provide http server
		di.Provide(NewServeMux), // provide http serve mux
		// controllers as []Controller group
		di.Provide(NewOrderController, di.As(new(Controller))),
		di.Provide(NewUserController, di.As(new(Controller))),
	)
	// handle container errors
	if err != nil {
		log.Fatal(err)
	}
	// invoke function
	if err := c.Invoke(StartServer); err != nil {
		log.Fatal(err)
	}
}

Full code available here.

Questions

If you have any questions, feel free to create an issue.