Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework ObjectContext re-usage

I'm learning EF now and have a question regarding the ObjectContext:

Should I create instance of ObjectContext for every query (function) when I access the database?

Or it's better to create it once (singleton) and reuse it?

Before EF I was using enterprise library data access block and created instance of dataacess for DataAccess function...

like image 226
verror Avatar asked Apr 27 '10 19:04

verror


1 Answers

I think the most common way is to use it per request. Create it at the beginning, do what you need (most of the time these are operation that require common ObjectContext), dispose at the end. Most of DI frameworks support this scenario, but you can also use HttpModule to create context and place it in HttpContext.Current.Items. That is simple example:

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)
    {
        var context = new MyEntities();
        HttpContext.Current.Items[@"MyEntities"] = context;
    }
}
like image 131
LukLed Avatar answered Sep 19 '22 07:09

LukLed