Book Image

Hands-On Dependency Injection in Go

By : Corey Scott
Book Image

Hands-On Dependency Injection in Go

By: Corey Scott

Overview of this book

Hands-On Dependency Injection in Go takes you on a journey, teaching you about refactoring existing code to adopt dependency injection (DI) using various methods available in Go. Of the six methods introduced in this book, some are conventional, such as constructor or method injection, and some unconventional, such as just-in-time or config injection. Each method is explained in detail, focusing on their strengths and weaknesses, and is followed with a step-by-step example of how to apply it. With plenty of examples, you will learn how to leverage DI to transform code into something simple and flexible. You will also discover how to generate and leverage the dependency graph to spot and eliminate issues. Throughout the book, you will learn to leverage DI in combination with test stubs and mocks to test otherwise tricky or impossible scenarios. Hands-On Dependency Injection in Go takes a pragmatic approach and focuses heavily on the code, user experience, and how to achieve long-term benefits through incremental changes. By the end of this book, you will have produced clean code that’s easy to test.
Table of Contents (15 chapters)

Constructor injection

When an object requires a dependency to work, the easiest way to ensure that dependency is always available is to require all users to supply it as a parameter to the object's constructor. This is known as constructor injection.

Let's work through an example where we will extract a dependency, generalize it, and achieve constructor injection. Say we are we are building a website for an online community. For this site, we wish to send an email to new users when they sign up. The code for this could be like 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)
}

We've made the *Mailer private to ensure proper encapsulation of the internals of the class. We can inject the *Mailer dependency...