Tuesday, September 17, 2013

Is it wise to dispose of my DBContext object before page render?

I am using DBContext extensivly in my asp.net web site project. What I typically do is I have an instance of the dbcontext that is available to the page class and I instantiate that on page load and use it throughout the code, I am not disposing of it however. Would it be wise for me to use the Pre_Render event on the page to dispose of the dbcontext (I would assume that it is done being used at that point?)
Thanks for any tips.
SOLUTION
So I ended up writing a little extension class for my Dotnetnuke modules that handles my dbcontext for me, seems to work good, but I have only rolled it out in a few modules so far.
public class ModuleExt : PortalModuleBase
{
    private BPEntities _ent;
    public BPEntities ent 
    {
        get{
            if (_ent == null)
            {
                _ent = new BPEntities();
            }
            return _ent;
        }
    }
    protected void Page_PreRender(object sender, EventArgs e)
    {
        ent.Dispose();
    }
}
This will enable me to just go ahead an use the ent object (my DBContext) and not worry about disposing as it is done for me on pre render.
share|edit
add comment (requires 50 reputation)
You may certainly do that, if you wish, but you'll need to keep one thing in mind: If you ever, at any point, want to reference a child object/collection from that object you'll need to make sure that it's hydrated before you dispose of the context. Otherwise, you will get a exception telling you that the context has been disposed already.
Some people will say to just have a single context through the application, and that is certainly a valid approach as well, but I much prefer what you're doing right now. I don't like having database connections open all of the time.
share|edit
Cool, All of my classes extend the same base class (I am working with DotNetNuke modules) so I wrote a quickie extension class for the module base class (see above) – box86rowh Apr 18 at 13:41
add comment (requires 50 reputation)

No comments:

Post a Comment