谷歌/电线 : Is this a use case for the Singleton pattern?

标签 go dependency-injection

以下代码段声明了两个具有共同依赖关系的 google/wire 初始化程序。强制只创建一个配置实例的最佳方法是什么?

我可以将共享依赖项向下传递给 InitializeStorageHandler 函数,但如果我的理解是正确的,那将破坏 DI 的目的。

当然,我也可以使用单例模式。我不确定这是否是做事的“Go-Way”。有最佳实践吗?

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

这与 wire 一致,如 issue 77 ,其中提到“Wire 非常适合提供单例”。

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.

在这种情况下,从 How singleton pattern works with Golang 中检查“Jefferson Otoni Lima ” : sync.Onceinit() function可以帮助在“Go-way”中安全地构建单例。

关于谷歌/电线 : Is this a use case for the Singleton pattern?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54963188/

相关文章:

http - 监听 "0.0.0.0:80"和 ":80"有什么区别?

reflection - 如何使用反射在golang中创建具有给定名称(字符串)的数组

AngularJS:服务、提供商、工厂

java - 具有循环依赖的 HK2 注入(inject)

.net - 使用 DI 传递同一接口(interface)的多个实现

dependency-injection - 如何在 .NET Core 的该层绑定(bind)服务 dll 的依赖项

docker - 如何在本地安装引用为 github.com 地址的 Golang 包

html - Golang xml解码html表

go - 通用函数来获取 Go 中任何结构的大小

c# - 手动注册所有类(class)还是有自动方式?