Spring:删除单例
我正在对一个调用的类进行单元测试
ContextRegistry.GetContext().GetObject("ISomething")
,如果未定义 ISomething 也没关系。 所以我正在尝试两种方式进行测试。 由于此定义通常来自 app.config 文件,并且我不想在测试之间编辑该文件,因此我使用 [TestFixtureSetUp] 和 [TestFixtureTearDown] 来注册单例、测试,然后我想'取消注册。 这注册得很好:
...ObjectFactory.RegisterSingleton("ISomething", new SomethingMOCK());
我可以检查它是否存在:
if (...ObjectFactory.ContainsSingleton("ISomething"))
但我似乎无法删除我注册的单例。 我尝试使用 null:
...ObjectFactory.RegisterSingleton("ISomething", null);
但这会抛出异常。 有没有更好的办法?
I am unit testing a class that calls
ContextRegistry.GetContext().GetObject("ISomething")
and it's ok if an ISomething isn't defined. So I am trying to test it both ways. Since this definition normally comes from the app.config file and I don't want to edit that file between tests, I'm using [TestFixtureSetUp] and [TestFixtureTearDown] to register the singleton, test, and then I'd like to 'un'-register it. This registers it just fine:
...ObjectFactory.RegisterSingleton("ISomething", new SomethingMOCK());
and I can check to see if it is there:
if (...ObjectFactory.ContainsSingleton("ISomething"))
but I can't seem to REMOVE the singleton I registered. I tried using null:
...ObjectFactory.RegisterSingleton("ISomething", null);
but this throws. Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我所知,不存在这样的功能。 无论如何,这会很棘手。 如果单例在最终被删除之前已经连接到其他对象,那么语义应该是什么? 可能无法将对象属性重新设置为 null,因为您不能假设受影响的属性允许使用 null。 如果对象是通过构造函数注入连接的,甚至可能没有 setter 方法。
As far as I know, no such feature exists. It would be tricky, anyway. What should be the semantics if the singleton has been wired to other objects already, before it is removed eventually? Re-setting object properties to null might not be possible as you cannot assume that null is allowed for the affected properties. If the object is wired via constructor injection, there might not even be a setter method.
除此之外,您始终可以使用 new XmlApplicationContext(" assembly://myconfigresource") 实例化自己的应用程序上下文,您可能还想查看 Spring.NET 对此的单元测试支持。 参考文档包含专门的章节:http://www.springframework。 net/doc-latest/reference/html/testing.html
hth,
埃里希
Aside that you can always instantiate your own application context using new XmlApplicationContext("assembly://myconfigresource"), you might also want to check out Spring.NET's Unit Testing support for this. The reference documenation contains a dedicated chapter: http://www.springframework.net/doc-latest/reference/html/testing.html
hth,
Erich
正如已经提到的:开箱即用是不可能的,但您可以通过代码轻松完成此操作,而无需接触 Spring.net。 只需使用代理模式并允许删除/更新委托目标,例如通过简单的获取/设置属性。 您所需要的只是一种获取 IoC 容器创建的对象的方法。
As already mentioned: It is not possible out of the box, but you can do this easyly via code without touching Spring.net. Just use a proxy pattern and allow the removal/update of the delegate target, e.g. through a simple get/set property. All you need is a way to get the created object of your IoC-Container.