WorldofASP.NET : ASP.NET Directory, Tutorial, Hosting, and Source Code
You are 1 of 209 users


Storing Contextual Data in Web and non-Web applications

Blogger : ASP.NET Blogs
All posts : All posts by ASP.NET Blogs
Category : ASP.NET
Blogged date : 2008 Sep 18

In Asp.Net apps, we are used to storing data in the current context.  Objects that are specific to the currently executing Request, like a User object retrieved a database, or another object that you want to make globally available without requiring multiple database trips, can benefit from this.

But what about this situation in non-web applications?  Or what about situations like an assembly that needs to have this contextual caching logic coded into it, but needs to be used from both web and non-web applications?

Below is an example of a static property that stores a User object, which is retrieved from a database, in the current HttpContext.  If it is already available in Context, it simply returns it.

image

 

What will happen if this property is accessed from a non-Asp.Net application, such as a windows service?  HttpContext.Current will return null, and we will get an exception.

We could simply store a static field in this class and access that if HttpContext.Current is null. But if that application has more than one thread, such as a Windows Service that is hosting a WCF Service, the static field will be shared across all threads.

Right?

Right - Unless we add the [System.Threading.ThreadStaticAttribute] to it!

Below is the updated property that will work in both kinds of applications:

 

image

There you go - a property access to contextual variable that caches for the length of the current thread, and isolated to the current thread.

Awesome!


Read comments or post a reply to : Storing Contextual Data in Web and non-Web applications
Page 270 of 1924
Next | Last

.NET News Categories








Legend : - Within 3 Days - Within 6 Days - Within 9 Days

Home | Add Resources | Sponsored Listings | Advertise with Us | SiteMap 1 | SiteMap 2 | Link To Us | Contact Us
© 2002-2008 Worldofasp.net ASP.NET Directory, Hosting and Tutorials | All rights reserved
Our Partners : ASP.NET Web Hosting | Windows Web Hosting | ASP.NET Hosting | Phone Card | PHP Directory | Bangkok Hotels |Calling Card