When to call Dispose in Entity Framework?

In my application, I use Spring.Net for IoC. Service objects are called from ASP.Net files to perform CRUD operations using this service object. For example, I have a CustomerService to perform all CRUD operations in the Customer table. I use entity structure and entities are injected .. my question is where can I call the dispose method?

As far as I understood from the API documentation, if I don't call Dispose (), there is no guarantee that this will be garbage collection! So where and how to do it?

Service class example:

 public class CustomerService
{
    public ecommEntities entities = {get; set;}

    public bool AddCustomer(Customer customer)
    {
        try
        {
            entities.AddToCustomer(customer);
            entities.SaveChanges();
            return true;
        }
        catch (Exception e)
        {
            log.Error("Error occured during creation of new customer: " + e.Message + e.StackTrace);
            return false;
        }            
    }

    public bool UpdateCustomer(Customer customer)
    {
        entities.SaveChanges();
        return true;
    }

public bool DeleteCustomer(Customer customer)
.
.
.   

And I just create a CustomerService object in a partial ASP class and call the necessary methods.

Thanks in advance for best practice and ideas.

Hi,

Abdel Rauf

+1
source share
2

HttpModule , :

public class MyEntitiesHttpModule : IHttpModule
{
    public void Init(HttpApplication application)
    {
        application.BeginRequest += ApplicationBeginRequest;
        application.EndRequest += ApplicationEndRequest;
    }

    private void ApplicationEndRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.Items[@"MyEntities"] != null)
            ((MyEntities)HttpContext.Current.Items[@"MyEntities"]).Dispose();
    }

    private static void ApplicationBeginRequest(Object source, EventArgs e)
    {
        //TextWriter logFile = File.CreateText(HttpContext.Current.Server.MapPath("~/sqllogfile.txt"));
        var context = new MyEntities();
        //context.Log = logFile;
        HttpContext.Current.Items[@"MyEntities"] = context;
    }
}

. HttpContext.Current.Items Ninject . , Spring.Net ObjectContext, , . Sprint.Net - , . , .

+2

@LukLed (+1), HTTP- . , , Dispose() NInject, Spring.Net, , . HttpContext.Current -.

(@Abdel) , :

API, Dispose(), , !

. Dispose() (, ). Dispose() .

+2

All Articles