jwaliszko
jwaliszko

Reputation: 17064

MVC actual controller vs filterContext.Controller

I have abstract BaseController, which basically looks like below:

public abstract class BaseController : Controller
{
    public IDisposable Resource { get; protected set; }      

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if(Resource != null)
        {
            Resource.Dispose();
        }

        var baseController = filterContext.Controller as BaseController;
        if (baseController != null && baseController.Resource != null)
        {
            baseController.Resource.Dispose();
        }
    }
}

Inside OnActionExecuted event, I want to dispose Resource object. Is it enough to execute Dispose on Resource ? Do I have to check also for Resource in the Controller from filterContext ?

In debugger in my case that this is the same object, but is it always the same one ? What is it used for ?

Upvotes: 1

Views: 1530

Answers (2)

Jon
Jon

Reputation: 16718

It is the same object. The Controller property can be useful in action filters - they also get an ActionExecutedContext in OnActionExecuted - and you're not in the controller there.

Upvotes: 1

Mark van Straten
Mark van Straten

Reputation: 9425

If it is still the same your controller will be constructed for every request (ASP.NET MVC Controller Lifecycle). Then you could just dispose your resource in the dispose of your controller (ASP MVC: When is IController Dispose() called?)

Upvotes: 1

Related Questions