Mikey Mouse
Mikey Mouse

Reputation: 3098

Is it a good idea to store my DataContext in Session Memory?

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?

Upvotes: 3

Views: 695

Answers (2)

Knaģis
Knaģis

Reputation: 21485

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).

Upvotes: 4

Iain Galloway
Iain Galloway

Reputation: 19190

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

Upvotes: 3

Related Questions