When to call Dispose in Entity Framework?

六眼飞鱼酱① 提交于 2019-12-07 17:36:30

I have HttpModule in my application, which takes care of creating and disposing of context:

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;
    }
}

It creates it at the beginning of request and disposes at the end. Context is taken from HttpContext.Current.Items by Ninject and injected into my service object. I don't know how exactly it works with Spring.Net and what is your approach to creating ObjectContext, but I hope this answer will help. If Sprint.Net supports per request lifetime and doesn't need any modules, it propably takes care of disposing too. In other case, you can do it like here.

@LukLed is generally correct (+1) that the HTTP request is the correct scope. However, I very much doubt explicit code is required to call Dispose() with either NInject or Spring.Net as both of these should already be disposing instances they manage. HttpContext.Current is as good a place to store the reference as anything.

However, you (@Abdel) are wrong to say:

As far as I understood from the API documentations, unless I call Dispose() there is no guaranty it will be garbage collected!

This is just not right. Dispose() makes the collection somewhat more optimal and provides for deterministic release of unmanaged resources (e.g., your DB connection). But everything will eventually be collected, with or without calling Dispose().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!