CA2000和依赖注入

Mic*_*eld 6 c# code-analysis asp.net-mvc-3

我正在使用一个相当简单的DI模式将我的数据存储库注入到我的控制器类中,并且我在每个模式下都获得了CA2000代码分析警告(在丢失范围之前Dispose对象).我知道为什么警告正在发生,并且通常可以弄清楚如何解决它,但在这种情况下我无法弄清楚

  1. 如何在对象创建和返回方法之间抛出异常,或者
  2. 在哪里我可以放try/finally块来摆脱错误.

在我放弃并抑制所有地方的警告信息之前,有没有更好的方法来实现同样的效果,而不会导致潜在的不受干扰的对象?

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();
            }
        }
    }
 }
Run Code Online (Sandbox Code Playgroud)

Ste*_*tty 1

如果您使用 ASP.Net MVC,您可以让您的控制器实现IDisposable,管道将负责为您处理它。请参阅ASP MVC:何时调用 IController Dispose()?