如何判断一个命名实例是否在 StructureMap 2.6 的容器中?
我之前使用的是 SM 2.5.3。我有一些代码存储了一个对象的命名实例,如下所示:
ObjectFactory.Configure(x =>
x.ForRequestedType<T>()
.TheDefault.IsThis(item)
.WithName(itemName));
然后,要从容器中请求其中一项,我会这样做:
return ObjectFactory.GetNamedInstance<T>(key);
如果特定的命名实例不在容器中,这就会崩溃,我捕获异常并返回 null。这就是我如何判断容器中是否已放入某些内容的方法(正在使用它来缓存小块数据)。
但是,我昨天将代码更新到了 2.6,现在它总是返回“T”的实例,即使容器中不存在命名实例。即使是新的 TryGetInstance() 方法也能做到这一点。所以我的问题是,如何判断命名实例实际上不在容器中?我注意到检索非命名实例的行为并非如此。
这就是我的新注册码的样子:
ObjectFactory.Configure(x => x.For<T>().Use(item).Named(itemName));
如果有人可以告诉我我做错了什么,或者有更好的建议,我将非常感激!
I was previously using SM 2.5.3. I had some code that stored a named instance of an object that looked like this:
ObjectFactory.Configure(x =>
x.ForRequestedType<T>()
.TheDefault.IsThis(item)
.WithName(itemName));
Then to request one of the items from the container, I would do:
return ObjectFactory.GetNamedInstance<T>(key);
If the particular named instance wasn't in the container, this would blow up and I caught the exception and returned null. This was how I could tell if something had been put in the container yet or not (was using it for caching small pieces of data).
However, I updated the code to 2.6 yesterday, and now it always returns an instance of whatever "T" is, even if the named instance does not exist in the container. Even the new TryGetInstance() method does this. So my question is, how do I tell if the named instance is NOT in fact in the container? I noticed that retrieving non-named instances does not behave this way.
This is what my new registration code looks like:
ObjectFactory.Configure(x => x.For<T>().Use(item).Named(itemName));
If anyone can tell me what I'm doing wrong, or has a better suggestion for doing this, I'd really appreciate it!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找到了解决方案。当从容器中检索命名实例时,我现在使用 Model 对象的功能来检查命名实例是否存在:
这也使我能够摆脱之前的 try...catch 块,这是一个好东西。不过,如果有人有任何其他建议,我想听听。
谢谢!
I found a solution. When retrieving the named instance from the container, I now use the features of the Model object to check if the named instance is there:
This also allows me to get rid of the try...catch block that I had before, which is a good thing. Still, if anyone has any other suggestions, I'd like to hear them.
Thanks!