1

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 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I think the OP is asking if his custom ViewResult can implement IDisposable.
...and if it does, whether MVC framework will call Dispose on it.
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!
0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.