使用 StructureMap,如何使用 InstanceScope.Singleton 显式触发对象的重新实例化?
我有一个集成测试工具,我想在每次测试之后和之前拆解并重新实例化我在 StructureMap 中注册的一些单例范围对象。
这样我就可以模拟实际的运行时环境,但不会将单例的状态从一个测试传递到另一个测试。也许这不是进行集成测试的好方法,但我已经没有其他解决方案了(请阅读任何建议)。
那么可以重新实例化具有 InstanceScope.Singleton 的对象吗?
使用 StructureMap 重新实例化单例范围对象的最佳方法是什么?
I have an integration test harness where I want to teardown and then re-instantiate some of the singleton-scoped objects I've registered with StructureMap, after and before each test.
This way I can simulate the actual run time environment, but not have the singleton's state being passed from one test to another. Maybe this isn't a great way to do an integration test, but I'm running out of alternative solutions (read open to any advice).
So can an object with InstanceScope.Singleton
, be re-instantiated?
What's the best way to do re-instantiate a singleton-scoped object with StructureMap?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不是 StructureMap 用户,但一般来说,在 IoC 容器中,您不应该尝试这样做。考虑一个依赖于另一个单例y的单例x。现在重新实例化y。但是x仍然保留对y旧实例的引用!
单例的生命周期应该与其容器相同,因此如果您想杀死单例的实例,则必须杀死其容器。您可以使用 嵌套容器。
I'm not much of a StructureMap user, but in IoC containers in general, you shouldn't try to do this. Think of a singleton x that depends on another singleton y. Now re-instantiate y. But x would still hold a reference to the old instance of y!
The lifetime of a singleton is supposed to be the same as its container, so if you want to kill an instance of a singleton, you'll have to kill its container. You can scope this by using a nested container.
ObjectFactory.Initialize 将重新初始化容器配置。在您的测试设置中执行此操作。
ObjectFactory.Initialize will re-initialise the container configuration. Do that in your test setup.