Sobes.tech
Senior

What is the difference between Dependency Injection and Dependency Inversion?

sobes.tech AI

Answer from AI

Dependency Injection (DI) is a design pattern where an object's dependencies are provided from outside rather than created internally. This makes it easy to change dependency implementations and simplifies testing.

The Dependency Inversion Principle (DIP) is one of the SOLID principles, which states that:

  • High-level modules should not depend on low-level modules; both should depend on abstractions.
  • Abstractions should not depend on details; details should depend on abstractions.

DI is a way to implement DIP. That is, DIP is an architectural principle, and DI is a specific method of dependency injection that helps follow this principle.

Example in Go:

// Abstraction
type Notifier interface {
    Notify(message string)
}

// Concrete implementation
type EmailNotifier struct {}
func (e EmailNotifier) Notify(message string) {
    fmt.Println("Sending email:", message)
}

// Client
type UserService struct {
    notifier Notifier
}

// Dependency injection via constructor (DI)
func NewUserService(n Notifier) *UserService {
    return &UserService{notifier: n}
}

func (u *UserService) SendNotification(msg string) {
    u.notifier.Notify(msg)
}

Here, DIP is followed by depending on the Notifier interface, and DI is achieved by passing a specific implementation from outside.