How to use Wire in golang for dependency injection

  • 這裡就不比較各個 dependency injection 的優缺點,只專注在 Wire 身上

參考 Wire 官方。完整實戰應用可以參考 todo-app

Installation

安裝所需要的執行檔。

1
go get github.com/google/wire/cmd/wire

常常有人裝完在 $GOPATH/bin 裡,是看得到執行檔的,但是在 Terminal 卻不能執行。
請注意,將 $GOPATH/bin 加入 $PATH 中,不會我也沒辦法了

How to use

直接上個 sample code 吧。順便測試一下 HexoGist tag 功能。

Install in your project with gomodule

You can create a sample project then execute go mod init and install wire.

1
go get -u github.com/google/wire

Generate wire code using Makefile

You can use Makefile to generate wire code.

1
2
3
.PHONY: gen-wire
gen-wire:
@wire gen ./...

Sample code

In the code using golang build tags like wireinject tag.

In real case

You might be need to inject a business service into your api layer. So you can create a ProviderSet for your business service.

So you can create an interface called HealthBiz and create a struct called impl then implement the interface.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package business

type HealthBiz interface {
Readiness() bool
}

type impl struct {}

func (i *impl) Readiness() bool {
return true
}

func NewBusinessImpl() HealthBiz {
return &impl{}
}

var ProviderSet = wire.NewSet(NewBusinessImpl)

you can add business.ProviderSet in your wire’s set.

1
var providerSet = wire.NewSet(business.ProviderSet)

Then you can inject the business in your api layer. It needs same return type and inject type.

1
2
3
4
5
package api

type impl struct {
biz business.HealthBiz
}