Search code examples
c#asp.netlinq-to-sqldata-access-layerdatacontext

Linq2Sql static Datacontext in DAL


I am new to Linq to sql. And my question is simple.

Is it a good idea to have DataContext as public static member in DAL to act as singleton?


Solution

  • I generally try to group functionality together for a Data Access class and make that class IDisposable. Then you Create your DataContext in your constructor and in your dispose method you run your .dispose() call on the DataContext.

    So then when you need something from that class you can wrap it in a using statement, and make a bunch of calls all using the same DataContext.

    It's pretty much the same effect as using a Static DataContext, but means you don't forget to close down the connection, and it seems a bit more OO than making things static.

        public class MyDataAccessClass: IDisposable
        {
          private readonly DbDataContext _dbContext;
    
          public MyDataAccessClass()
          {
              _dbContext = new DbDataContext ();
          }
    
          public void Dispose()
          {
            _dbContext.Dispose();
          }
    
          public List<CoolData> GetStuff()
          {
               var d = _dbContext.CallStuff();
               return d;
          }
        }
    

    Then in your class

       using(var d = new MyDataAccessClass())
       {
             //Make lots of calls to different methods of d here and you'll reuse your DataContext
       }