【发布时间】:2016-03-25 03:14:54
【问题描述】:
我正在开发 asp.net mvc-4 Web 应用程序和实体框架 5.0。现在我对 Dispose 在我的应用程序中的工作方式感到困惑。目前我有以下设置:-
-我有一个 APIRepository 类,其中包含多个使用 WebClient() 进行外部 API 调用的方法。而且我没有在这个类中定义任何 Dispose 方法。
public class APIRepository
{
public string AddTicket(string title, string technichian,string account,string site,string description,string mode,string requestor)
{
//code goes here
using (var client = new WebClient())
{
}
return result;
}
//code goes here
}
-我有一个包含我的数据访问逻辑的 Repository 类,它启动了我的DbContext,我在这个类中定义了一个 Dispose 方法。
public class Repository
{
private MyEntities my = new MyEntities();
//code goes here...
public void Dispose()
{
my.Dispose();
}
-我有一个 Controller 类,它启动两个存储库类:-
[RequireHttps]
public class ServerController : Controller
{
Repository repository = new Repository();
APIRepository APIrepository = new APIRepository();
//code goes here
protected override void Dispose(bool disposing)
{
if (disposing)
{
repository.Dispose();
}
base.Dispose(disposing);
}
现在我对我当前的项目有以下问题:-
根据我对 Dispose 工作原理的理解,当一个 action 方法调用 View 时,asp.net mvc 会自动调用我当前 Controller 类中的 Dispose 方法。它反过来调用我的存储库中的 Dispose 方法,这将确保数据库连接已关闭。那么我的理解有效吗?
在我的情况下,我是否需要在我的 APIRepository() 中有一个 Dispose 方法,正如我提到的,这个存储库只有
WebClient()调用以与 3rd 方应用程序集成,它将返回对象或简单字符串到action方法。??有哪些操作需要Disposed?据我所知,在我的存储库类中调用
my.Dispose();将确保数据库连接已关闭.. 但是否还有其他操作需要处理?比如发起WebClient()或者通过我的action方法返回一个JSON?除了返回 View 之外,还有哪些操作会调用我的 Controller 类中的 Dispose 方法?
【问题讨论】:
-
我 100% 确定您可以通过在此站点中搜索找到您问题的所有答案,可能会分成几个问题。
-
看来你不是继承自
IDisposable -
@Jonesopolis 现在我的 ServerController 类扩展了 Controller 类。并且Controller类实现了IDisposable接口(这些是在asp.net mvc中开箱即用的,当我创建一个新的Controller类时),然后在ServerController中我覆盖了Dispose方法..所以不知道你是什么意思通过“看来您不是从 IDisposable 继承的”???谢谢
标签: c# asp.net .net asp.net-mvc dispose