<p>Is there any way to create a global container which can hold different objects like code below?</p>
<p>//global container<br/>
injector := inject.New()<br/>
injector.Map("db", DB{}) </p>
<p>// get by name, from anywhere in code<br/>
db := injector.Get("db") </p>
<p>The instance should be created only on Get and it should only be generated the first time, rest of the time it should be reused. </p>
<hr/>**评论:**<br/><br/>FUZxxl: <pre><p>What problem do you want to solve with this?</p></pre>mathewvp: <pre><p>Dependency Injection</p></pre>FUZxxl: <pre><p>Look at the pattern used by the <code>image</code> package, specifically the <a href="http://golang.org/pkg/image/#RegisterFormat" rel="nofollow"><code>RegisterFormat()</code> function</a> and how it's supposed to be used. Maybe you can implement something similar?</p></pre>champioj: <pre><p>Why not use a global map hidden in the inject package?
What's the use of inject.New()? You want something global, but you initialize a new instance. Does that mean that some data is instantiated and some are shard globally?
That seems quite complicated.</p></pre>FUZxxl: <pre><p>Just use a global variable for such cases. That's “good enough” but please take care of race-conditions.</p></pre>natefinch: <pre><p>No, you can't do that in a generic and type safe way, and it's frankly a terrible idea. This is just asking for runtime errors galore. You can of course write a function per value that constructs the value at first request. That's a much safer and more sane solution.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传