代码分析警告 CA2000:在对象“new ContainerControlledLifetimeManager()”上调用 Dispose

发布于 2024-09-09 06:10:58 字数 534 浏览 2 评论 0原文

我在一些单元测试中收到代码分析警告:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

压抑⊿情绪 2024-09-16 06:10:58

CA2000 实现对于在一次性实例“移交”到另一个方法之前可能引发异常的情况非常敏感。在这种情况下,即使容器最终会在注册期间没有发生异常的情况下负责清理生命周期管理器,但在 RegisterInstance 调用之前或在调用期间但在容器将生命周期管理器添加到其容器之前,也可能会发生异常。自己的内部状态。

为了解决这种可能性,您可以使用如下代码(尽管我自己可能不会为此烦恼,除非该配置做了一些重要的事情):

var loggingServiceMock = new Mock<ILoggingService>();

var lifetimeManager = new ContainerControlledLifetimeManager();
try
{
    this.unityContainer.RegisterInstance<ILoggingService>(loggingServiceMock.Object, lifetimeManager);
}
catch
{
    lifetimeManager.Dispose();
    throw;
}

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):

var loggingServiceMock = new Mock<ILoggingService>();

var lifetimeManager = new ContainerControlledLifetimeManager();
try
{
    this.unityContainer.RegisterInstance<ILoggingService>(loggingServiceMock.Object, lifetimeManager);
}
catch
{
    lifetimeManager.Dispose();
    throw;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文