For many programmers and programming languages, constructor injection is their default method for DI. It is perhaps no surprise therefore that it has numerous advantages.
Separation from the dependency life cycle—Constructor injection, like most DI methods, separates the life cycle management of the dependency from the object that it's being injected into. By doing this, the object becomes more straightforward and easier to understand.
Easy to implement—As we saw in our previous examples, it's easy to take this:
// WelcomeSender sends a Welcome email to new users
type WelcomeSender struct {
Mailer *Mailer
}
func (w *WelcomeSender) Send(to string) error {
body := w.buildMessage()
return w.Mailer.Send(to, body)
}
And change it to this:
func NewWelcomeSender(mailer *Mailer) *WelcomeSender {
return &WelcomeSender...