在控制器中创建对象,确保了IDisposable呼叫,并移交给查看 [英] Ensuring IDisposable call on objects created in the controller and handed off to view

查看:143
本文介绍了在控制器中创建对象,确保了IDisposable呼叫,并移交给查看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直都知道,所有的优秀的程序员调用Dispose实现了IDisposable,情况点EF的ObjectContext类的任何对象。

I have always known that all good programmers call Dispose on any object that implements IDisposable, case in point the ObjectContext class in EF.

我是新来asp.net的MVC所以这可能是一个noob问题但在这里不用...

I am new to asp.net mvc so this may be a noob question but here goes...

    public ActionResult Index()
    {
        using (var db = new MyObjectContext())
        {
            return View(db.People);
        }
    }

如果我运行这个code我得到的,因为ObjectContext的已被释放的视图呈现数据之前采取行动的错误(的ObjectDisposedException)。是否有一种不同的方法吗?如何确保我的对象得到尽快处理掉越好?

If I run this code I get an error (ObjectDisposedException) because the ObjectContext has been disposed of before the View takes action on the data. Is there a different approach here? How can I ensure my objects get disposed of as soon as possible?

推荐答案

重写Controller.Dispose()方法,并在那里你的对象处置:

Override the Controller.Dispose() method and dispose of your object in there:

private IDisposable _objectToDispose;

public ActionResult Index() {
  var db = new MyObjectContext();
  _objectToDispose = db;
  return View(db.People);  
}

protected override void Dispose(bool disposing) {
  if (disposing && _objectToDispose != null) {
    _objectToDispose.Dispose();
  }
  base.Dispose(disposing);
}

MVC框架会自动在请求结束调用Controller.Dispose()。

The MVC framework will automatically call Controller.Dispose() at the end of the request.

这篇关于在控制器中创建对象,确保了IDisposable呼叫,并移交给查看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆