none
The using statement & Static method RRS feed

  • Question

  •  

    Hi All,

     

       I am creating a data access layer using LINQ to SQL and am thinking about taking one of the following paths.

     

      Would it be right to create a DataContext object of class scope (member variable in a class) inherit from IDisposable so that the user can then call my data access layer class in a using statement & hold on to the DataContext variable for the life of the class

     

     or

     

     Have a static class with each static method calling the DataContext in  a using statement.

     

     which option would be better to take (also from a performance point of view)

     

    Thanks in advance

     

    Regards

     

    tribal

    Wednesday, April 16, 2008 9:02 AM

Answers

  • It is going to be difficult to be super-prescriptive here because the specific approach will depend on your application, but try to keep the DataContext short lived. Fire one up when you need to use it, perform the work and then dispose. You could go with using statements that instantiate the DataContext, or some surrounding type that you do this on like you point out as an approach.

     

    Hope this helps.

    Faisal Mohamood | Program Manager | LINQ to SQL

    Wednesday, April 30, 2008 3:47 AM
    Moderator

All replies

  • Please, correct me anybody if I am wrong, but static classes usage is considarible only when you need to create some helper auxiliary class.

     

    Also from performance prospective it would be better to maintain instance of class instead static method, because in case of sequential DB updates you will be able to use the same DataContext instance.

    Wednesday, April 16, 2008 10:02 AM
  •  

    Check out the link below on Rick Stahl's weblog. He suggests using the single DataContext in scope approach just as you said Vitaliy and its coming from a web dev perspective so you've got a pretty strong point, does anyone have any other ideas...

     

    http://www.west-wind.com/weblog/posts/246222.aspx

     

    Thursday, April 17, 2008 4:14 PM
  • It is going to be difficult to be super-prescriptive here because the specific approach will depend on your application, but try to keep the DataContext short lived. Fire one up when you need to use it, perform the work and then dispose. You could go with using statements that instantiate the DataContext, or some surrounding type that you do this on like you point out as an approach.

     

    Hope this helps.

    Faisal Mohamood | Program Manager | LINQ to SQL

    Wednesday, April 30, 2008 3:47 AM
    Moderator
  •  

    My app will be using this library in 2 scenarios

     

    1.  an ASP.NET app and

    2.  in a console exe run from a windows service.

     

      Will this be the right thing in both the cases

     

    Thanks

    Thursday, May 1, 2008 12:09 PM