Share object instance between web service invocations
I have an object that has relatively high initializ开发者_JAVA百科ation 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?
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.
精彩评论