Sunday, September 18, 2016

Using dependency injection in Go

There are three ways to handle dependency injection done in Go.

Explicit, by sending the dependency to your function / method call.



Creating a wrapper to handle injecting that dependency into the code of the of the which can then be used everywhere else in the application.

Adding a field to the structure you already have with the dependency you need.

I've used the log.Printf function especially because logging can become a dependency.
Instead of importing the "log" package then calling log.Printf every time, you should be inject that as a dependency.
This can be useful in order to allow the existence of two (or more) log levels or for swapping out logging libraries without changing the code itself every time you do it.

No comments :