Search code examples
c#linqevalidisposableusing

using statement in conjunction with Repeater DataBinds and events


In relation to the below code, does the using statement take into consideration objects called via _ItemDataBound methods and Eval methods when finding objects that need disposing of? Or will it try to dispose before attached events and evals are fired since they occur later in the life cycle?

In other words, does it only dispose the datacontext after all the Evals and attached Events to the repeater are called or will this cause datacontext has already been disposed errors?

protected void Page_Load(object sender, EventArgs e)
{
    using (EventManager manager = new EventManager())
    {
        EventDates = manager.GetWhatsOn(Request.QueryString["category"]);

        rptEventDates.DataSource = EventDates;
        rptEventDates.DataBind();
    }

...

public class EventManager : IDisposable
{
    private MainDataContext db;
    public EventManager()
    {
        db = new MainDataContext();
    }

    ....other methods....

    public void Dispose()
    {
        db.Dispose();
    }
}

Solution

  • In relation to the below code, does the using statement take into consideration objects called via _ItemDataBound methods and Eval methods when finding objects that need disposing of?

    No. It doesn't "find" objects to dispose at all - it just disposes of the object referred to in the first part of the statement. So your code is broadly equivalent to:

    EventManager manager = new EventManager();
    try
    {
        EventDates = manager.GetWhatsOn(Request.QueryString["category"]);
    
        rptEventDates.DataSource = EventDates;
        rptEventDates.DataBind();
    }
    finally
    {
        manager.Dispose();
    }
    

    Nothing else will be disposed, but the EventManager itself definitely will be disposed.

    If anything requires the resource not to be disposed of until later, you shouldn't use a using statement.