how to automatically dispose managed and unmanaged objects on fromClosed event?

i am improving speed and resource usage of an huge HIS application that have more than 200 winForms and they use entityContext like these :

private void someMethod()
{
    var context = new entityContext();
    var qry = context.someTable.Where(x=>x.condition);//bring thousands of records
    ...
    ... do some thing with result

    ...
    //EOF method. here is problem :
    /*
     * is context will be free all the records that brings to ram 
     * in the end of method without using  context.Dispose()?
     * i think NO!
     */
}

is there any way to find all of the entityContext object that created in the form and dispose them?

if i use at winForms Closed event this.Dispose(true); is it enough to dispose all of them?

public class myForm : System.Windows.Forms.Form
{
    protected override void OnClosed(EventArgs e)
    {
        base.OnClosed(e);

        /*
         * TODO: 
         *      find all entityContext objects and dispose them
         */ 

        this.Dispose(true);
    }
}

i don't have time to edit all codes to wrap all entityContextobjects in a using{} clause or add manually context.Dispose() to them or etc ...

i am looking for a way to dispose all of them in the OnClosed() event is these possible?

Answers


The recommended way is to wrap all your context objects in a using{} clause. This way they will be automatically disposed when exiting the using. Also the norm is to use short lived context objects.

Searching with reflection for all instances of DbContext (or any Type for that matter) is not possible in .NET (at least not easily) as far as I know. And reflection, even if this is possible, will hurt your performance.

Having context objects as singletons in repositories (if this pattern has been used) can also help you towards disposing them especially if your repos are implementing IDisposable.


Need Your Help

Are there any other way to fill a Datatable in ADO.Net without using dataadaptor.Fill method?

ado.net datatable fill

Are there any other fast way to fill a Data table in ADO.Net without using Data adaptor.Fill method?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.