Dependency Injection in Go

Definitions

Dependency injection represents the D in SOLID principles. Quoting from wikipedia:

Why is dependency injection important in practice?

The answer depends — and it really depends how much of your domain requires very heavy dependencies.

allow customers to store their code and run them in some sort of containerized environment.

In this product, our ubiquitous language might have the following entities:

Playing out what tech we’ll use

If we stick to boring technology:

How will we test these?

If we want to have a good testing experience, we’ll strive for the
following:

# just works without any dependencies at all.
go test ./…
# does integration testing using env vars or flags.
env $(cat .env) go test /… -tags integration

It’s all about the interface

If we changed the code above to instead rely on an interface:

So what about dependency injection?

Ultimately, because we’ve designed our system to take in well defined services instead of concrete implementations, we can simply change how we initialize our main file:

Will we end up writing a lot of boilerplate mock code?

Probably yes — and it really depends how much of your domain requires very heavy dependencies.

Footnotes

- In certain cases, certain companies have even gone and implemented an entire mock implementation for their customers to use. For example, LetsEncrypt shipped pebble which is a miniaturized version of their real service offering. Hashicorp ships with an in-memory vault for easy testing as well.
- When should you reach for sophisticated tools like wire? I personally would try to avoid those tools as they add a lot of unnecessary complexity in terms of reasoning about your code — but again, YMMV.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Cyril David

Cyril David

software engineer at auth0, writing code for humans, with humans.