代码分析警告 CA2000:在对象“new ContainerControlledLifetimeManager()”上调用 Dispose
我在一些单元测试中收到代码分析警告:
WidgetManagerTests.cs (40): CA2000 : Microsoft.Reliability:在方法中 'WidgetManagerTests.TestInitialize()', 调用 System.IDisposable.Dispose 对象“新” ContainerControlledLifetimeManager()' 在所有对它的引用都消失之前 范围。
我正在使用 Unity 和 Moq,这是有问题的行:
var loggingServiceMock = new Mock<ILoggingService>();
this.unityContainer.RegisterInstance<ILoggingService>(loggingServiceMock.Object, new ContainerControlledLifetimeManager());
I'm getting a code analysis warning on some of my unit tests:
WidgetManagerTests.cs (40): CA2000 :
Microsoft.Reliability : In method
'WidgetManagerTests.TestInitialize()',
call System.IDisposable.Dispose on
object 'new
ContainerControlledLifetimeManager()'
before all references to it are out of
scope.
I'm using Unity and Moq, this is the offending line:
var loggingServiceMock = new Mock<ILoggingService>();
this.unityContainer.RegisterInstance<ILoggingService>(loggingServiceMock.Object, new ContainerControlledLifetimeManager());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
CA2000 实现对于在一次性实例“移交”到另一个方法之前可能引发异常的情况非常敏感。在这种情况下,即使容器最终会在注册期间没有发生异常的情况下负责清理生命周期管理器,但在 RegisterInstance 调用之前或在调用期间但在容器将生命周期管理器添加到其容器之前,也可能会发生异常。自己的内部状态。
为了解决这种可能性,您可以使用如下代码(尽管我自己可能不会为此烦恼,除非该配置做了一些重要的事情):
The CA2000 implementation is very sensitive to cases where an exception might be thrown before a disposable instance is "handed off" to another method. In this case, even though the container will eventually take care of cleaning up the lifetime manager if no exceptions occur during registration, it's possible an exception to occur either before the RegisterInstance call or within the call but before the container add the lifetime manager to its own internal state.
To address this possibility, you could use code like the following (although I probably wouldn't bother with this myself unless the disposition did something significant):