Home > .NET > CA2000 on default MVC GetAccountController method

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.

Advertisements
Categories: .NET
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: