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)

Advantages of config injection

Given that config injection is an expanded form of constructor and method injections, the advantages of the other methods also apply here. In this section, we will discuss only the additional benefits that are specific to this method.

It's excellent for decoupling from a config packageWhen we have a config package that loads from a single place, such as a file, then this package tends to become a dependency for many of the other packages in the system. When considering the Single responsibility principle section from Chapter 2SOLID Design Principles for Go, we recognize that the more users a package or object has, the more resistant and/or difficult it is to change.

With config injection, we are also defining our requirements in a local interface and leveraging Go's implicit interfaces and the dependency inversion principle...