Sobes.tech
Junior — Middle

What methods can be used to implement dependency injection in code?

sobes.tech AI

Answer from AI

Dependency Injection (DI) in Go can be implemented in several ways, considering the language features:

  1. Through function or constructor parameters — the most common and straightforward method. Dependencies are explicitly passed when creating an object or calling a function.
type Service struct {
    repo Repository
}

func NewService(r Repository) *Service {
    return &Service{repo: r}
}
  1. Using interfaces — allows easy substitution of dependency implementations for testing or extension.

  2. DI packages — there are third-party libraries (e.g., Uber Fx, Google Wire) that help automate dependency injection, but their use is not mandatory.

  3. Global variables or singletons — a less preferred method due to issues with testability and maintainability.

In Go, explicit injection through parameters is usually preferred, as it enhances code readability and simplicity.

What methods can be used to implement dependency… - sobes.tech