views:

47

answers:

1

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());
A: 

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;
}
Nicole Calinoiu
Thanks, this works though I used a using statement to make the code a bit simpler.
tjrobinson
A using statement in place of the above try/catch will result in the lifetime manager being disposed even if there is no exception. This would presumably not result in the behaviour you would expect when no exception is thrown. Have you tested the behaviour of the code after your modification?
Nicole Calinoiu