0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Wireに入門する

0
Last updated at Posted at 2025-08-02

Wireとは?

  • Googleが開発したDIを自動でやってくれるツールのこと
  • Goで使われる

Wireの使い方

基本的にはwire.BuildにDIを行いたいプロパイダー(コンストラクタのこと)を渡して上げるだけでwireが必要な依存関係を自動で注入してくれてwire.gen.goというファイルが生成される。
例えば、アプリケーション層、ユースケース層、レポジトリ層という3つからなるアプリケーションを作成する時、以下のような感じでwireに値を渡してあげる

main.go
//go:build wireinject
// +build wireinject

package server

import "github.com/google/wire"
// 各レイヤーの構造体を定義する
type App struct {
	App Aplication
}

type Aplication struct {
	Usecase Usecase
}
type Usecase struct {
	Repository Repository
}
type Repository struct {
	RepositoryImpl RepositoryImpl
}

type RepositoryImpl struct {
	findAll() ([]string, error)
}
// wire.Setにプロパイダーを渡すことで特定のコンテキストに応じてプロパイダーのセットができる
// あくまでプロパイダーのセットを作っているだけなのでプロパイダーをwire.Buildに直接渡してもいい
var AppSet = wire.NewSet(
	wire.Struct(new(App), "*"),
	wire.Struct(new(Aplication), "*"),
	wire.Struct(new(Usecase), "*"),
	wire.Struct(new(Repository), "*"),
	wire.Struct(new(RepositoryImpl), "*"),
)
// wire.Buildにプロパイダーを渡してあげるとDIをやってくれる
func InitializeApp() *App {
	wire.Build(AppSet)
	return &App{}
}

func main() {
    InitializeApp()
}

準備ができたら、go tool wire .をやると以下のファイルが自動生成される

wire_gen.go
// Code generated by Wire. DO NOT EDIT.

//go:generate go run -mod=mod github.com/google/wire/cmd/wire
//go:build !wireinject
// +build !wireinject

package server

import (
	"github.com/google/wire"
)

// Injectors from di.go:

func InitializeApp() *App {
	repositoryImpl := RepositoryImpl{}
	repository := Repository{
		RepositoryImpl: repositoryImpl,
	}
	usecase := Usecase{
		Repository: repository,
	}
	aplication := Aplication{
		Usecase: usecase,
	}
	app := &App{
		App: aplication,
	}
	return app
}

// di.go:

type App struct {
	App Aplication
}

type Aplication struct {
	Usecase Usecase
}

type Usecase struct {
	Repository Repository
}

type Repository struct {
	RepositoryImpl RepositoryImpl
}

type RepositoryImpl struct {
}

var AppSet = wire.NewSet(wire.Struct(new(App), "*"), wire.Struct(new(Aplication), "*"), wire.Struct(new(Usecase), "*"), wire.Struct(new(Repository), "*"), wire.Struct(new(RepositoryImpl), "*"))

wire.goに下記の記述を行うことでwire_gen.goで生成されたInitializeApp()が呼ばれてDIが完了したアプリケーションを利用することができる

//go:build wireinject
// +build wireinject

まとめ

今回はGoogleによって開発されたDIをいい感じにしてくれるwireの使い方を備忘録としてまとめました。
*初心者エンジニアの書き殴りなのであくまでも参考程度に留めておいていただけると幸いです

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?