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 吧。順便測試一下 Hexo 的 Gist 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 |
|
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 | package business |
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 | package api |