Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CA2000 and Dependency Injection

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

  1. How there is any possibility of an exception being thrown in between object creation and the method returning, or
  2. 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();
            }
        }
    }
 }
like image 908
Michael Edenfield Avatar asked Dec 21 '12 15:12

Michael Edenfield


1 Answers

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?.

like image 103
Steve Czetty Avatar answered Sep 30 '22 20:09

Steve Czetty