1. Write at the front
When reviewing other people's code before, I saw the use of wire library. But at that time, it was mainly analyzing logical problems, and I didn’t learn much about the usage of wire library. I happened to learn it recently while taking advantage of the gap in testing!
Note: Wire library /google/wire/cmd/wire is a Go language library developed by Google for dependency injection. Wire adopts compile-time dependency injection, aiming to reduce runtime overhead and improve application performance and maintainability.
2. Introduction
2.1 Feature Introduction
Compile-time dependency injection: Wire parses dependencies at compile time and generates code to satisfy dependencies. This means there is no reflection or other overhead at runtime, thus improving performance.
Type safety:Wire utilizes Go's type system to ensure the correctness of dependencies. This can catch errors at compile time, not at runtime.
Simple and easy to use: Wire's API is simple to design, easy to understand and use. With clear configuration, complex dependencies can be easily managed.
Generate code:Wire creates the required constructor and initialization code using code generation. Users only need to define dependencies, and Wire will automatically generate code that satisfies these dependencies.
2.2 Using functions to explain
-
Allows you to combine multiple provider functions and organize dependencies.
-
Used to define the Injector's construction logic and automatically generate code that satisfies dependencies.
3. Code example
Storage layer (store/):
// Define a message storage interfacetype Store interface { Save(msg Message) error Get() (Message, error) } // ProvideStore binds InMemoryStore to the Store interfacefunc ProvideStore() Store { return NewInMemoryStore() } // StoreSet is Wire's provider setvar StoreSet = ( ProvideStore, )
Service layer (service/):
// MessageService depends on the Store interfacetype MessageService struct { store } // Wire Provider: Tell Wire how to construct MessageServicefunc NewMessageService(s ) *MessageService
Application layer ():
// MessageApp depends on MessageServicetype MessageApp struct { msgService * } // Wire Provider: Tell Wire how to construct MessageAppfunc NewMessageApp(service *) *MessageApp
Wire configuration ():
// Define dependency injection rulesfunc InitializeMessageApp() (*MessageApp, error) { ( , // Provides the implementation of the Store interface , // Provide the MessageService constructor NewMessageApp, // Provide MessageApp constructor ) return &MessageApp{}, nil // This return value will be replaced by the code generated by Wire}
Dependencies:
- MessageApp Dependencies → MessageService
- MessageService Dependencies → Store Interface
- The Store interface is implemented by InMemoryStore
Wire's workflow:
- InitializeMessageApp function in Analysis
- Check all dependencies
- Generate wire_gen.go file, containing the dependency initialization code in the correct order
- Automatically create and inject all dependencies in the correct order when run
// Code generated by Wire. DO NOT EDIT. //go:generate go run -mod=mod /google/wire/cmd/wire //go:build !wireinject // +build !wireinject package main import ( "example/wire/service" "example/wire/store" ) // Injectors from : // InitializeMessageApp uses Wire to inject dependencies and initialize the applicationfunc InitializeMessageApp() (*MessageApp, error) { storeStore := () messageService := (storeStore) messageApp := NewMessageApp(messageService) return messageApp, nil }
Advantages of this dependency injection method:
- Decoupling: Interaction between components through interfaces, without directly relying on specific implementations
- Testable: Easy to replace simulation implementations for testing
- Maintenance: Clear dependencies and easy to manage
- Compilation-time check: You can find dependency configuration problems at compile time
4. Silent thoughts
I was anxious for a while ago whether AI would replace me, but from another perspective, if AI can be used more fully, can it be saved by a lot of time spent before, so that I can do a lot of meaningful things:
- She was too young at that time and didn't know that all the gifts given by fate had already marked the price behind her back.
- Don’t blame yourself for her past self, she was also confused when she stood alone in the fog.
- The time in New York is 3 hours earlier than California time, but California has not slowed down. Obama retired at the age of 55, but Trump became president at the age of 70. Everyone in the world has their own time zone. Some people seem to be walking in front of you, some people seem to be walking behind you, but in fact everyone has their own time zone and path. Don’t be jealous or ridiculed them. Everyone is in their own time zone, so are you.
5. References
GitHub - google/wire: Compile-time Dependency Injection for Go
Wire User Guide
Dependency Injection Tool-wire | Li Wenzhou's Blog
This is the end of this article about the use of golang wire library. For more related contents of golang wire library, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!