Global container for objects

agolangf · · 580 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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(&#34;db&#34;, DB{}) </p> <p>// get by name, from anywhere in code<br/> db := injector.Get(&#34;db&#34;) </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&#39;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&#39;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&#39;s “good enough” but please take care of race-conditions.</p></pre>natefinch: <pre><p>No, you can&#39;t do that in a generic and type safe way, and it&#39;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&#39;s a much safer and more sane solution.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

580 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传