Home > Blockchain >  is it possible to make simple dependency injection in golang
is it possible to make simple dependency injection in golang

Time:09-04

I come from node.js and nest.js world, where DI is simple and provided by a framework. Can or should I consider using dependency injection when building services on go?

CodePudding user response:

Yes, it is possible in Go.

A simple three-step DI system for Go:

Imagine you have a package A that shall not import package B but call some functions from that package; for example, functions Load() and Save().

  1. In package A, define an interface type with these functions.
type Storage interface {
    Load(string) []byte
    Save(string, []byte)
}

A type in package A can then refer to that interface and call Load() and Save() without knowing the actual receivers of these calls.

type StructA struct {
    content []byte
    storage Storage
}

func NewStructA(s Storage) *StructA {
    return &StructA{
        content: ...,
        storage: s,
    }
}

func (a *StructA) Save(name string) {
    a.storage.Save(name, a.content)
}

func (a *StructA) Load(name string) {
    a.content = a.storage.Load(name)
}
  1. In package B, implement Load() and Save().
type StoreB struct {
    poem []byte
}

func (b *StoreB) Save(name string, contents []byte) {
    // let's say StoreB contains a map called data
    b.data[name] = contents
}

func (b *StoreB) Load(name string) []byte {
    return b.data[name]
}
  1. In package main, connect the wires.
storage := B.StructB
a := A.NewStructA(storage)
a.Save()

Now you can add other storage provides (package C, D,...) and wire them up in main.

storage2 := C.StructC
a2 := A.NewStructA(storage2)
a2.Save()

A more detailed discussion is here: https://appliedgo.net/di/

CodePudding user response:

Yes, you should consider DI in go, DI has same advantages in go as any other language. It can be easily achieved in go by using interfaces.

  • Related