This document discusses different approaches for dependency injection in Go including:
1. Using package-level new functions to create dependencies and services.
2. Creating a "Super Factory" structure that embeds multiple dependency factories and can be used to initialize services and their dependencies with a uniform invocation mechanism.
3. Initializing a "Test Super Factory" for unit testing that can mock dependencies.
It analyzes the tradeoffs of different approaches and references additional resources on the topic.
3. Abstractions over Implementations
Inject or Lookup Dependencies
Lifecycle of Services and Dependencies
Loose Coupling & Unit Testing
Avoid Unutilized Dependencies
4. Code against interfaces
Contracts & Data Model in a “model” package
Ben Johnson’s “Root” package
No cyclical dependencies
References:
https://medium.com/@benbjohnson/standard-package-layout-7cdbc8391fc1
https://appliedgo.net/di/
https://8thlight.com/blog/uncle-bob/2012/08/13/the-clean-architecture.html
Credit:
Robert Wechsler (www.robertwechsler.com) for permission to use image of “Circular
Bike”.
5. Contracts to be implemented
Service has a Dependency
Sometimes, it also has Another-Dependency
10. Pass New Function
Func type in Model Package
Function not Instance
New Instance then Invoke
https://martinfowler.com/articles/injection.html#UsingAServiceLocator
31. Super Factory contains many items
Restrict access to only the relevant factories
Create a custom factory interface,
Inherently compatible with SuperFactory