views:

495

answers:

2

Is it legit to have your ASP.NET MVC ViewResult class implement IDisposable? My custom view result has a stream member that I want to guarantee is closed once it has been streamed back to the client. Does ASP.NET MVC honor IDiposable on ViewResult implementations?

thanks!

+2  A: 

ViewResult does not implement IDisposable interface. Look at ASP.NET MVC source:

ViewResult.cs:

namespace System.Web.Mvc {
    using System;
    using System.Globalization;
    using System.Text;
    using System.Web.Mvc.Resources;

    public class ViewResult : ViewResultBase {
...

ViewResultBase.cs:

namespace System.Web.Mvc {
    using System;
    using System.Diagnostics.CodeAnalysis;

    public abstract class ViewResultBase : ActionResult {
...

ActionResult.cs:

namespace System.Web.Mvc {

    public abstract class ActionResult {

        public abstract void ExecuteResult(ControllerContext context);

    }

}

UPDATED:

If you implement IDisposable interface in your class (derived from ViewResult) the Dispose() (IDisposable.Dispose()) will not be invoked by ASP.NET MVC framework.

eu-ge-ne
I think the OP is asking if his custom ViewResult can implement IDisposable.
DSO
...and if it does, whether MVC framework will call Dispose on it.
DSO
This is a serious flaw in MVC! I hope they take care of it. For example, FileStreamResult will not dispose of the stream passed to it!
erikkallen
A: 

If you want this behavior you can get it by extending ControllerActionInvoker. I believe you can do something like:

// warning: untested
public class DisposableControllerActionInvoker : ContollerActionInvoker
{
  public override void InvokeActionResult(
      ControllerContext controllerContext, ActionResult actionResult) 
  {
    base.InvokeActionResult(controllerContext, actionResult);
    var disposable = actionResult as IDisposable;
    if(disposable != null) 
    {
      disposable.Dispose();
    }
  }
}

You'll then need to get your ControllerActionInvoker added to the Controller, which you can do using a custom controller factory (there's probably a simpler way but I'm not familiar).

Talljoe