The following snippet declares two google/wire initializers which have a dependency in common. What is the best way to enforce that only one instance of the configuration is created?
I could pass the shared dependency down to the InitializeStorageHandler function, but that would defeat the purpose of DI if my understanding is correct.
Of course, I could also use the Singleton pattern. I'm not sure if this is the "Go-Way" of doing things. Is there a best practice?
package api
import (
"../storage"
"../config"
"github.com/google/wire"
)
func InitializeServer() (*Server, error) {
panic(wire.Build(config.NewConfiguration, NewServer))
}
func InitializeStorageHandler() *StorageHandler {
panic(wire.Build(config.NewConfiguration, storage.NewStorage, storage.NewService, NewStorageHandler))
}
Of course, I could also use the Singleton pattern
That would be consistent with wire, as in issue 77, which mentions that "Wire is very much designed for provision of singletons".
As discussed in issue 21:
Wire intentionally does not have a notion of subcomponents at the moment.
In talking with the Dagger team, we discovered that subcomponents and scopes introduce a fair amount of complexity.As you say, you can get much the same behavior by returning the singletons from the first injector that creates them and then pass them to later injectors. This has the benefit of making the dataflow explicit, which for the examples we came up with, seemed like a net win.
That said, we're very curious to see how folks will use Wire in real-world applications: if this does not scale, we might have to revisit.I realized after looking more closely at your sample that the component itself is stateful (a detail I had forgotten about Dagger). My explanation above is still largely applicable: we want state to be explicit.
In that case, check out "How singleton pattern works with Golang" from Jefferson Otoni Lima: sync.Once
or the init()
function can help building a singleton securely, in a "Go-way".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With