Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better dependency injection pattern in golang?

Tags:

interface

go

Given this code:

package main

import (
    "fmt"
)

type datstr string

type Guy interface {
   SomeDumbGuy() string
}

func (d *datstr) SomeDumbGuy() string {
  return "some guy"
}

func someConsumer(g Guy) {
  fmt.Println("Hello, " + g.SomeDumbGuy())
}

func main() {
    var d datstr
    someConsumer(&d)
}

Is the wiring of components together that's done in main the right way to wire a dependency together? It seems like I'm over using this a bit in my code. Is there a common pattern better than this, or am I overthinking it?

like image 785
Justin Thomas Avatar asked Jan 27 '17 17:01

Justin Thomas


People also ask

Does Golang do dependency injection?

Dependency injection is a technique in which an object receives other objects that it depends on, called dependencies. Typically, the receiving object is called a client and the passed-in ('injected') object is called a service. If you take a look at the code above, we have a message, a greeter, and an event.

Which type of dependency injection is better?

Setter Injection is the preferred choice when a number of dependencies to be injected is a lot more than normal, if some of those arguments are optional than using a Builder design pattern is also a good option. In Summary, both Setter Injection and Constructor Injection have their own advantages and disadvantages.

Does dependency injection improve performance?

The only code that uses a dependency directly is the one that instantiates an object of a specific class that implements the interface. The dependency injection technique enables you to improve this even further. It provides a way to separate the creation of an object from its usage.


2 Answers

The best practice is not to use a DI library. Go is meant to be a simple language that is easy to follow. A DI library/framework will abstract that away from you (and to some extent make DI magical).

like image 63
Zeeshan Avatar answered Oct 17 '22 23:10

Zeeshan


Google's Wire looks promising. There're some articles about it:

  • Compile-time Dependency Injection With Go Cloud's Wire

  • Go Dependency Injection with Wire

like image 37
William Yeh Avatar answered Oct 17 '22 22:10

William Yeh