Source:
(1)Compile-time Dependency Injection With Go Cloud’s Wire
(2)github.com/google/wire
(3)denpendency injection
(3)Portable Cloud Programming with Go Cloud
(4)github.com/google/go-cloud
Digest:
1. Dependency Injection:
Dependency injection is a standard technique for producing flexible and loosely coupled code, by explicitly providing components with all of the dependencies they need to work.
2. Dependency Injection Tools:
Dependency injection tools like Wire aim to simplify the management of initialization code. You describe your services and their dependencies, either as code or as configuration, then Wire processes the resulting graph to fugure out ordering and how to pass each service what it needs. Make changes to an application's dependencies by changing a function signature or adding or removing an initializer, and then let Wire do the tedious work of generating initialization code for the entire dependency graph.
3. Wire – Hasn’t this been done already?
There are a number of dependency injection frameworks out there. For Go, Uber's dig and Facebook's inject both use reflection to do runtime dependency injection. Wire was primarily inspired by Java's Dagger2, and uses code generation rather than reflection or service locators.
We think this approach has serveral advantages:
Runtime dependency injection can be hard to follow and debug when the dependency graph gets complex. Using code generation means that the initialization code that's executed at runtime is regular, idiomatic Go code that's easy to understand and debug. Nothing is obfuscated by an intervening framework doing "magic". In particular, problems like forgetting a dependency become compile-time errors, not run-time errors.
Unlike service locators, there's no need to make up arbitrary names or keys to register services. Wire uses Go types to connect components with their dependencies.
It's easier to avoid dependency bloat. Wire's generated code will only import the dependencies you need, so your binary won't have unused imports. Runtime dependency injectors can't identify unused dependencies until runtime.
Wire's dependency graph is knowable statically, which provides opportunities for tooling and visualization.
3. Wire – How does it work?
Wire has two basic concepts: providers and injectors.
Providers are ordinary Go functions that "provide" values given their dependencies, which are described simply as parameters to the function.
Providers that are commonly used together can be grouped into ProviderSets.
Injectors are generated functions that call providers in dependency order. You write the injector's signature, including any needed inputs as arguments, and insert a call to wire.Build with the list of providers or provider sets that are needed to construct the end result.