我正在使用一个相当简单的 DI 模式将我的数据存储库注入(inject)到我的 Controller 类中,并且我在每个类上都收到了 CA2000 代码分析警告(在丢失范围之前处理对象)。我知道为什么会出现警告,并且通常可以弄清楚如何解决它,但在这种情况下我无法弄清楚
- 如何在对象创建和方法返回之间抛出异常,或者
- 我可以在哪里放置
try/finally
block 来消除错误。
在我放弃并在所有地方抑制警告消息之前,有没有更好的方法来实现同样的效果,而不会导致潜在的未处理对象?
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();
}
}
}
}
最佳答案
如果您使用的是 ASP.Net MVC,您可以让您的 Controller 实现 IDisposable
,管道将负责为您处理它。参见 ASP MVC: When is IController Dispose() called? .
关于c# - CA2000 和依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13993088/