How to Use dig for Reflection-Based DI in Go

Use the github.com/uber-go/dig library for reflection-based DI in Go, as the dig command is for DNS lookups.

You cannot use dig for reflection-based dependency injection in Go because dig is a DNS lookup tool, not a Go library. Use the github.com/uber-go/dig package instead, which provides a reflection-based DI container. Install it with go get github.com/uber-go/dig and initialize a container with dig.New(). Register dependencies using c.Provide and retrieve them with c.Invoke.

package main

import (
	"fmt"
	"github.com/uber-go/dig"
)

type Service interface {
	Do() string
}

type serviceImpl struct{}

func (s *serviceImpl) Do() string {
	return "Hello"
}

func main() {
	c := dig.New()
	c.Provide(func() *serviceImpl { return &serviceImpl{} })
	c.Invoke(func(s Service) {
		fmt.Println(s.Do())
	})
}