3

I'm writing a pretty straightforward ASP.net project. It's using a Linq2Sql DataContext to access stored procedures. There's a IDisposable class that creates a new DataContext in it's constructor and disposes it in it's dispose.

Whenever possible I group together requests inside the:

    using(var dc = new MyDataAccessClass())
    {
       //All the data requests in here
    }

    // Do stuff with the data here

So there are quite a few of these throughout the code mostly in the UserControls, and I was just thinking if it would make sense to Create a single DataAccess Class in the PageLoad of the starting page (Or the master page), store it in Session Memory, and reference in all the UserControls and whatnot, then dispose of it in the PreRender stage.

So here's my question, is this a bad idea? I imagine this would involve a few dangling connections to the database, as exceptions or debugging would stop the PreRender running. Maybe a check on the MasterPage's Load to see if there's anything in that session Variable and to dispose it if it is, would sort it.

Or is there a smarter way to share a DataContext throughout the page life cycle without your DBA wanting to hit you with your keyboard?

Mikey Mouse
  • 2,968
  • 2
  • 26
  • 44
  • 1
    Take a look at this awser: http://stackoverflow.com/questions/226127/multiple-single-instance-of-linq-to-sql-datacontext – Felipe Oriani Nov 05 '12 at 11:23
  • @FelipeOriani Dang, I promise I spent a good 60 seconds looking for a duplicate. Sorry bout that. – Mikey Mouse Nov 05 '12 at 11:25
  • I think store the context in session is a bad idea. I don't know if it is the best practise but you can store it in System.Web.HttpContext.Current.Items. At least it has only request scope. – maralfol Nov 05 '12 at 11:30

2 Answers2

4

Session is most probably not a good idea - you have to worry about concurrency, recovering broken connections etc. Also the approach of disposing the context in PreRender is not the best since in case of an exception the PreRender handler will never execute.

System.Web.HttpContext.Current.Items is the only storage in ASP.NET that is alive only for the duration of a single request and also is handled in the rare situation when ASP.NET request is transferred between different threads in the middle of the execution.

You can use Application_EndRequest event in global.asax to dispose your connection correctly always (the EndRequest is also called after an Error).

Knaģis
  • 20,827
  • 7
  • 66
  • 80
3

In ASP.NET, your best bet is to create it once per request using a dependency injection framework.

See e.g. https://github.com/ninject/Ninject.Web.Common/wiki/Inrequestscope

Iain Galloway
  • 18,669
  • 6
  • 52
  • 73