Dependency Injection

Copper uses google/wire to enable dependency injection. Check out the introductory blog post to learn more about dependency injection and Wire.

In a Copper project, each package has a wire.go file. This file is autogenerated if you use the Copper CLI to create your package directories.

$ copper scaffold:pkg <package>

Example

Let's say you have the following struct that requires rockets.Queries and clogger.Logger for its methods.

type Launcher struct {
    rockets *rockets.Queries
    logger  clogger.Logger
}

func (l *Launcher) Launch(ctx context.Context, rocketID string) error {
    // ...    
}

To enable automating wiring up of all dependencies, create a constructor for the Launcher struct.

func NewLauncher(r *rockets.Queries, l clogger.Logger) *Launcher {
  return &Launcher{
    rockets: r,
    logger:  l,
  }
}

Finally, add the constructor to the package's WireModule defined in the wire.go file.

var WireModule = wire.NewSet(
    NewLauncher,
)

That's it! Copper + Wire will automatically pass in the correct dependencies to the NewLauncher constructor.

Last updated