CA2000 on default MVC GetAccountController method
I came across a tricky issue the other day after creating a new MVC3 project and associated unit test project.
After turning on Code Analysis, I was presented with
CA2000 : Microsoft.Reliability : In method ‘AccountControllerTest.GetAccountController()’, object ‘<>g__initLocalb’ is not disposed along all exception paths. Call System.IDisposable.Dispose on object ‘<>g__initLocalb’ before all references to it are out of scope.
To fix this Dispose issue, change the GetAccountController method to the below.
private static AccountController GetAccountController()
{
AccountController controller = null;
try
{
var requestContext = new RequestContext(new MockHttpContext(), new RouteData());
controller = new AccountController();
controller.FormsService = new MockFormsAuthenticationService();
controller.MembershipService = new MockMembershipService();
controller.Url = new UrlHelper(requestContext);
controller.ControllerContext = new ControllerContext
{
Controller = controller,
RequestContext = requestContext
};
}
finally
{
if (controller != null) controller.Dispose();
}
return controller;
}
Note that when constructing the AccountController, I have removed the object constructor.
While this took me a while to figure out, but using an object constructor on the Disposable object, actualy brings back the original error even though we are constructing within the try finally block.