Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more: , +
Hello Guys,

I read below post and confused what is the best way for datacontext creation and consumption ?

http://www.foliotek.com/devblog/avoid-static-variables-in-asp-net/[^]

I always thought that we should use singleton like below(+locking)

C#
private static ModelDataContext dataContext=null;
protected static ModelDataContext DataContext
{
      get
      {
           if(dataContext==null)
               dataContext = new ModelDataContext();
           return dataContext;
       }
 }






However in the article he says shortly ;

LINQ DataContexts cache some of the data and changes you make – you can quickly eat up memory if each instance isn’t disposed fairly quickly. TableAdapters hold open SQLConnections for reuse – so if you use enough classes of TableAdapters, you can have enough different static vars to tie up all of your db connections.

and suggests to use the model below

C#
protected static ModelDataContext DataContext
{
      get
      {
           if(System.Web.HttpContext.Current.Items["ModelDataContext"]==null)
               System.Web.HttpContext.Current.Items["ModelDataContext"] = new ModelDataContext();
           return (ModelDataContext)System.Web.HttpContext.Current.Items["ModelDataContext"];
       }
 }


What are your thoughts ?

Thanks
Posted
Comments
Maciej Los 12-Oct-15 12:20pm    
+5 for the question!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900