As a general rule, BP Service calls should depend only upon their input args, static information set during startup, and configuration settings. This helps them to function correctly when handling many concurrent requests from different users, because state values from one user's request won't leak into another user's state.

However, sometimes this rule leads to performance issues because the BP Service has to repeat the same operation, with the same results, on every request. For example, if every request has to query the database to look up some information about the current user, and that information rarely changes, then it's unnecessary load on the database server.

The AB_Cache class can be used to hold a value in memory for a short time, even across BP Service calls, and it will drop the value if it is not used within a configurable time period. The class is a wrapper around System.Runtime.Caching.MemoryCache, with added support for Regions.

private static ObjectCache _MyCache = new AB_Cache();
protected ObjectCache MyCache { get { return _MyCache; } }


MyCache.Set("mykey", "a value", new CacheItemPolicy { SlidingExpiration = new TimeSpan(0, 2, 0) }, "Region_A");
var val = MyCache.Get("mykey", "Region_A") as string;

This example sets up a cache with default options for memory limits and expiration time. The AB_Cache() constructor accepts MemoryCache's arguments for CacheMemoryLimitMegabytes, PhysicalMemoryLimitPercentage, and PollingInterval.

In the Set() call, a CacheItemPolicy is passed which sets a two minute expiration, and the Region argument provides a namespace for the key arguments. A typical use in a BP Service would be to use InputArgs.ap_UserID as the region, so that each user has their own namespace within the cache.

A service application may contain multiple cache objects, which should all be static fields so that they're retained for the life of the service process. Each cache object has its own memory use limits, and provides a separate storage for its own regions and keys.