Store LINQ context as query variable or not?

Is this a good way to use the LINQ context during a single HTTP request? In almost every request, I have some selections from the database and some inserts / updates. It is suitable for work, but I do not know how it will work with heavy traffic on servers and on servers with load balancing. Does anyone have any opinions / ideas on this way of maintaining context throughout the duration of a request?

public static AccountingDataContext Accounting { get { if (!HttpContext.Current.Items.Contains("AccountingDataContext")) { HttpContext.Current.Items.Add("AccountingDataContext", new AccountingDataContext(ConfigurationManager.ConnectionStrings["SQLServer.Accounting"].ConnectionString)); } return HttpContext.Current.Items["AccountingDataContext"] as AccountingDataContext; } } 
+4
source share
2 answers

All in all, this is a good idea at some levels. But you probably want to push the instance back from the Begin_Request event. With the integrated pipeline, you will initialize a rather expensive database context for each individual request to your site. Including favicon.ico, all of your style sheets and all of your images.

A better, simpler implementation of what only instantiates when something requests a context, Ayende example for ISIBernate ISession ; you can simply replace it with the appropriate bits to create an instance of your L2S context.

+3
source

I use Unity to inject dependencies, but the idea is the same:

 protected void Application_BeginRequest() { var childContainer = this.Container.CreateChildContainer(); HttpContext.Current.Items["container"] = childContainer; this.ControllerFactory.RegisterTypes(childContainer); } protected void Application_EndRequest() { var container = HttpContext.Current.Items["container"] as IUnityContainer; if (container != null) { container.Dispose(); } } 

A container is responsible for setting up several things, one of which is the data context. It works like a charm. I did not perform load balancing, but I can’t imagine that you are facing problems. The query gets its own context, which wraps one user connecting to the database. Nothing else that using the old school ADO.NET to access data.

+2
source

All Articles