开发者

Code Analysis warning CA2000: Call Dispose on 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.Disp开发者_如何学运维ose 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());


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜