gpt4 book ai didi

go - 使用 facebookgo 创建多个实例

转载 作者:IT王子 更新时间:2023-10-29 01:47:09 25 4
gpt4 key购买 nike

facebookgo 的正确使用方法是什么?图来实例化一个服务/依赖的多个实例?文档中的示例显示了实例化与 variable 之间的紧密耦合。 .但是,如果我的依赖关系是“有状态的”,以至于我不能在多个服务中使用单例,我如何让 facebookgo 每次都给我新的实例?

func main() {
var g inject.Graph
var s service.Impl
if err := g.Provide(&inject.Object{Value: library.NewDependency()},
&inject.Object{Value: &s}); err != nil {
fmt.Println("err in g.Provide: ", err)
}
if err := g.Populate(); err != nil {
fmt.Println("err in g.Populate: ", err)
}
s.Feature()

var s2 service.Impl
}

假设服务和库是一些具有一些实现的包。 "inject"是 facebookgo/inject 和 service.Impl 依赖于 library.Dependency。现在,我该如何解析 s2?

最佳答案

如果您使用 Dargo对于注入(inject)服务有作用域。例如 Singleton 和 PerLookup。在您的情况下,您可以在 PerLookup 范围内绑定(bind)一个服务,然后每次查找或注入(inject)时都会创建它。

默认情况下,事物被绑定(bind)到 Singleton 范围内,因此对于 PerLookup 范围内的事物,您必须在绑定(bind)语句中明确说明:

import "github.com/jwells131313/dargo/ioc"    

ioc.CreateAndBind(Example2LocatorName, func(binder ioc.Binder) error {
// binds the echo service into the locator in Singleton scope
binder.BindWithCreator(EchoServiceName, newEchoService)

// binds the logger service into the locator in PerLookup scope
binder.BindWithCreator(LoggerServiceName, newLogger).InScope(ioc.PerLookup)

return nil
})

关于go - 使用 facebookgo 创建多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48313616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com