I am using a fairly simple DI pattern to inject my data repository into my controller classes, and I'm getting the CA2000 code analysis warning (Dispose objects before losing scope) on every one of them. I know why the warning is happening, and can usually figure out how to fix it, but in this case I cannot figure out
try/finally
blocks to get rid of the error.Before I just give up and suppress the warning messages all over the place, is there a better way to achieve this same effect that doesn't result in a potential undisposed 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();
}
}
}
}
If you are using ASP.Net MVC, you can have your controller implement IDisposable
, and the pipeline will take care of disposing it for you. See ASP MVC: When is IController Dispose() called?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With