views:

30

answers:

2

I have a CustomRequestContext object that has to be disposed after each request. I create it in Page_Load and dispose of it in Page_Unload. The only issue is that in certain circumstances I need to call Server.Transfer to redirect to another aspx page instead. In this case, the object should not be unloaded until the new page is ready to be unloaded. What is the nicest way of achieving this?

A: 

create a custom PageBase class for all your asp.net pages as mention below and Dispose the CustomRequestContext on the Page_Load and Page_Unload event.

/// <summary>
/// Base of front end web pages.
/// </summary>
public class PageBase : System.Web.UI.Page
{

    /// <summary>
    /// Initializes a new instance of the Page class.
    /// </summary>
    public Page()
    {
        this.Load += new EventHandler(this.Page_Load);
        this.UnLoad += new EventHandler(this.Page_UnLoad);
    }

    /// <summary>
    /// Page Load
    /// </summary>
    /// <param name="sender">sender as object</param>
    /// <param name="e">Event arguments</param>
    private void Page_Load(object sender, EventArgs e)
    {
        try
        {
            //Dispose the object here, assuming it is IDisposable.
            //You can apply your own Disposition steps here..
            CustomRequestContext.Dispose();
        }
        catch
        {
            //handle the situation gracefully here.
        }
    }

    /// <summary>
    /// Page UnLoad
    /// </summary>
    /// <param name="sender">sender as object</param>
    /// <param name="e">Event arguments</param>
    private void Page_UnLoad(object sender, EventArgs e)
    {
        try
        {
            //Dispose the object here, assuming it is IDisposable.
            //You can apply your own Disposition steps here..
            CustomRequestContext.Dispose();
        }
        catch
        {
            //handle the situation gracefully here.
        }
    }
}
this. __curious_geek
You are disposing it in both the load and unload functions. Is your suggestion that I should just recreate the context object again instead of trying to save it?
Casebash
Nope. I just presented the idea of how you can dispose the object on the given events. It's upto you when to Dispose the object.
this. __curious_geek
A: 

I solved this problem by allowing the object to be owned by one page at a time. If I wanted to relinquish control from a page, I would set it equal to null and then it would not be released in the page's destructor.

Casebash