CA2000 and dependency injection

I use a fairly simple DI pattern to inject my data repository into my controller classes, and I get a CA2000 code analysis warning (delete objects before losing scope) on each of them. I know why this warning occurs, and usually can figure out how to fix it, but in this case I can not understand

  • How is there any possibility of throwing exceptions between object creation and the return method or
  • Where can I put try/finally blocks to get rid of the error.

Before I simply refuse and suppress warning messages everywhere, is there a better way to achieve the same effect that will not lead to a potential unallocated object?

 public class AccountController : Controller { public AccountController () : this(new SqlDataRepository()) { } public AccountController ( IDataRepository db ) { this.db = db ?? new SqlDataRepository(); // Lots of other initialization code here that I'd really like // to avoid duplicating in the other constructor. } protected override void Dispose(bool disposing) { if (disposing && (this.db != null)) { IDisposable temp = this.db as IDisposable; if (temp != null) { temp.Dispose(); } } } } 
+6
source share
2 answers

If you use ASP.Net MVC, you can implement your IDisposable controller, and the pipeline will take care of the disposal for you. See ASP MVC: When is IController Dispose () called? .

+1
source

Your repository implements IDisposable. Make your controller also implement IDisposable, and in the dispose method, clear your repository.

0
source

All Articles