views:

161

answers:

1

I have an object that has relatively high initialization cost that provides a thread-safe calculation method needed to process web service requests.

I'm looking for the best way to keep an initialized instance available between requests.

One method is to declare it as a static variable. It would then remain available until the AppDomain is recycled.

This is an older web service that does not use WCF, but converting is an option if that would provide a better solution.

Is there a better approach?

+1  A: 

What about caching the object in HttpRuntime.Cache?

MyObject val = (MyObject)HttpRuntime.Cache["MyCacheKey"];
if (val == null)
{
    val = // create your expensive object here
    HttpRuntime.Cache.Insert("MyCacheKey", val, null, 
      DateTime.Now.AddSeconds(3600), 
      System.Web.Caching.Cache.NoSlidingExpiration);
}

Here I leave it in the cache for up to an hour, but you can vary this as needed.

Keltex
Is the cache's lifecycle independent of each AppDomain's lifecycle (AppDomain processing the HTTP requests that is)?
Eric J.
@Eric J. It's independent of an individual HTTP Request. In other words, your service could handle 1000s of requests and the object would remain in the cache. If the App Domain recycles (daily or whatever you have setup in IIS), then the cached object is deleted. Likewise, the object isn't guaranteed to remain in the cache for it's expiration, this is dependent on available memory, etc.
Keltex
So this essentially provides the same lifecycle as a static object reference, but with the added flexibility that I can control expiration as can IIS if it needs to reclaim some memory?
Eric J.
@Eric J Yes. Exactly. I think this is the preferred method to use. Typically I set some expiration date on my cached objects though none is required. You can also set a sliding expiration so that if an object hasn't been requested in some period of time (say 20 minutes), then the cache purges the item.
Keltex