Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share object instance between web service invocations

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?

like image 587
Eric J. Avatar asked Feb 23 '10 23:02

Eric J.


1 Answers

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.

like image 165
Keltex Avatar answered Nov 15 '22 05:11

Keltex