Wednesday, December 14, 2016

Error CA2000 call System.IDisposable.Dispose on object

My code looked like


this.client.Setup(mock => mock.PostAsync(It.IsAny<IEnumerable<ids>>())).Returns(Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK)));

and i was getting the below style cop error

Severity Code Description Project File Line Suppression State
Error CA2000 In method 'MyMethod()', call System.IDisposable.Dispose on object 'new HttpResponseMessage(HttpStatusCode.OK)' before all references to it are out of scope. Catalog.Common.UnitTests code.cs 72 Active

To overcome this, if it is in single method, you can suppress the error

[SuppressMessage("Microsoft.Reliability",
                 "CA2000:DisposeObjectsBeforeLosingScope",
                 Justification = "Your reasons go here")]
OR you can change the code to be like below

this.client.Setup(mock => mock.PostAsync(It.IsAny<IEnumerable<ids>>())).Returns(Task.Run(() => { return new HttpResponseMessage(System.Net.HttpStatusCode.OK); }));

No comments:

Post a Comment