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
- How there is any possibility of an exception being thrown in between object creation and the method returning, or
- Where I can put
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();
}
}
}
}