Convert Figma logo to code with AI

google logowire

Compile-time Dependency Injection for Go

12,864
615
12,864
103

Top Related Projects

5,648

A dependency injection based application framework for Go.

1,801

⚙️ A dependency injection toolkit based on Go 1.18+ Generics.

1,406

Package inject provides a reflect based injector.

26,478

A standard library for microservices.

Quick Overview

Google Wire is a code generation tool that automates dependency injection in Go. It analyzes your source code to generate code that initializes complex dependency graphs, reducing boilerplate and simplifying the management of large-scale applications.

Pros

  • Reduces boilerplate code for dependency injection
  • Compile-time dependency injection, catching errors early
  • Improves code maintainability and readability
  • Integrates well with existing Go code and practices

Cons

  • Learning curve for developers new to dependency injection concepts
  • Requires additional build step to generate code
  • Limited flexibility compared to runtime dependency injection
  • May increase compile times for large projects

Code Examples

  1. Defining providers:
func NewServer(db *sql.DB) *Server {
    return &Server{db: db}
}

func NewDatabase() (*sql.DB, error) {
    return sql.Open("mysql", "user:password@/dbname")
}
  1. Defining an injector:
//+build wireinject

package main

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

func InitializeServer() (*Server, error) {
    wire.Build(NewServer, NewDatabase)
    return nil, nil
}
  1. Using the generated code:
func main() {
    server, err := InitializeServer()
    if err != nil {
        log.Fatal(err)
    }
    server.Run()
}

Getting Started

  1. Install Wire:

    go install github.com/google/wire/cmd/wire@latest
    
  2. Define your providers and injector (as shown in the code examples).

  3. Generate the wire_gen.go file:

    wire
    
  4. Use the generated InitializeServer() function in your main code.

  5. Build and run your application as usual.

Competitor Comparisons

5,648

A dependency injection based application framework for Go.

Pros of fx

  • Runtime dependency injection, allowing for dynamic configuration
  • Built-in lifecycle management for components
  • Supports both constructor and field injection

Cons of fx

  • Slower startup time due to runtime reflection
  • Potential for runtime errors if dependencies are misconfigured
  • Steeper learning curve for complex applications

Code Comparison

fx:

func NewHandler(lc fx.Lifecycle, logger *zap.Logger) *Handler {
    h := &Handler{logger: logger}
    lc.Append(fx.Hook{
        OnStart: func(context.Context) error {
            // Startup logic
        },
    })
    return h
}

wire:

func InitializeHandler(logger *zap.Logger) *Handler {
    return &Handler{logger: logger}
}

func InitializeApp() *App {
    wire.Build(NewLogger, InitializeHandler, NewApp)
    return nil
}

Key Differences

  • fx uses runtime dependency injection, while wire generates code at compile-time
  • fx provides built-in lifecycle management, whereas wire focuses solely on dependency injection
  • wire offers faster startup times and compile-time safety, but fx provides more flexibility and dynamic configuration options

Both libraries aim to simplify dependency management in Go applications, but they take different approaches. The choice between them depends on specific project requirements and preferences regarding runtime vs. compile-time behavior.

1,801

⚙️ A dependency injection toolkit based on Go 1.18+ Generics.

Pros of do

  • Supports runtime dependency injection, allowing for more dynamic configurations
  • Provides a simpler API with less boilerplate code
  • Offers built-in support for optional dependencies and default values

Cons of do

  • Less compile-time safety compared to Wire's static analysis
  • May have a slight performance overhead due to runtime reflection
  • Lacks some of Wire's advanced features like cleanup functions

Code Comparison

do:

container := do.New()
container.Provide(NewDatabase)
container.Provide(NewUserService)

err := container.Invoke(func(userService *UserService) {
    // Use userService
})

Wire:

func InitializeUserService() *UserService {
    wire.Build(NewDatabase, NewUserService)
    return nil
}

userService := InitializeUserService()

Summary

do offers a more flexible and runtime-oriented approach to dependency injection, with a simpler API and support for optional dependencies. However, it sacrifices some compile-time safety and performance optimizations that Wire provides. Wire, on the other hand, focuses on compile-time dependency injection with static analysis, offering better performance and safety at the cost of less flexibility and a more verbose setup.

1,406

Package inject provides a reflect based injector.

Pros of Inject

  • Runtime dependency injection, allowing for more flexibility and dynamic configuration
  • Supports method injection and field injection in addition to constructor injection
  • More mature and battle-tested in production environments

Cons of Inject

  • Slower performance due to runtime reflection
  • Requires more boilerplate code and annotations
  • No longer actively maintained (archived repository)

Code Comparison

Inject:

public class Car {
    @Inject
    private Engine engine;

    @Inject
    public Car(Wheels wheels) {
        // Constructor injection
    }
}

Wire:

func InitializeCar(engine *Engine, wheels *Wheels) *Car {
    return &Car{
        engine: engine,
        wheels: wheels,
    }
}

Key Differences

  • Wire uses compile-time dependency injection, while Inject uses runtime injection
  • Wire generates code, reducing runtime overhead and improving performance
  • Inject offers more flexibility with various injection types, while Wire focuses on constructor injection
  • Wire is actively maintained and developed by Google, whereas Inject is archived by Facebook
  • Wire is designed for Go, while Inject is for Java, reflecting different language paradigms and ecosystems

Both tools aim to simplify dependency management, but they take different approaches suited to their respective languages and use cases.

26,478

A standard library for microservices.

Pros of kit

  • Comprehensive microservices toolkit with a wide range of features
  • Supports multiple transport protocols (HTTP, gRPC, etc.)
  • Extensive middleware and instrumentation options

Cons of kit

  • Steeper learning curve due to its extensive feature set
  • Can be overkill for smaller projects or simple services
  • Requires more boilerplate code compared to wire

Code Comparison

kit example:

type Service interface {
    Hello(name string) (string, error)
}

func NewService() Service {
    return &service{}
}

wire example:

type Service struct {
    Greeter Greeter
}

func NewService(g Greeter) *Service {
    return &Service{Greeter: g}
}

Summary

kit is a comprehensive microservices toolkit offering a wide range of features, while wire focuses on compile-time dependency injection. kit provides more out-of-the-box functionality for building complex microservices, but may be overwhelming for simpler projects. wire, on the other hand, offers a more lightweight approach to managing dependencies, which can lead to cleaner and more maintainable code in certain scenarios. The choice between the two depends on the specific requirements and complexity of your project.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Wire: Automated Initialization in Go

Build Status godoc Coverage

Wire is a code generation tool that automates connecting components using dependency injection. Dependencies between components are represented in Wire as function parameters, encouraging explicit initialization instead of global variables. Because Wire operates without runtime state or reflection, code written to be used with Wire is useful even for hand-written initialization.

For an overview, see the introductory blog post.

Installing

Install Wire by running:

go install github.com/google/wire/cmd/wire@latest

and ensuring that $GOPATH/bin is added to your $PATH.

Documentation

Project status

As of version v0.3.0, Wire is beta and is considered feature complete. It works well for the tasks it was designed to perform, and we prefer to keep it as simple as possible.

We'll not be accepting new features at this time, but will gladly accept bug reports and fixes.

Community

For questions, please use GitHub Discussions.

This project is covered by the Go Code of Conduct.