Creating a cache
To improve the performance of your Sitecore application and extend the caching capabilities of Sitecore, you can create caches as needed.
Create a cache
You can create a cache with one of the following methods:
-
Use the
GetNamedInstance
method of the staticCacheManger
class:RequestResponseICache<string> cache = CacheManager.GetNamedInstance("global_cached_items", 1024, true);
-
Use dependency injection:
RequestResponseLazyResetable<BaseCacheManager> LazyInstance = ServiceLocator.GetRequiredResetableService<BaseCacheManager>(); ICache<string> cache = LazyInstance.Value.GetNamedInstance("global_cached_items", 1024, true);
Get a cache
To retrieve a cache, use the FindCacheByName
method of the CacheManager
class:
ICache<string> cache = CacheManager.FindCacheByName<string>("global_cached_items");
Add an item to a cache
To add a new item to the cache, use the Add
method:
cache.Add("key", "value");
If you add complex keys or objects to the cache, consider using the ICacheable
interface to define a size calculation inside the GetDataLength
method, avoiding expensive size calculations within the caching strategy.
Get a value from a cache
To get a value from a cache, use the GetValue
method:
object result = cache.GetValue("key");
If you have complex keys or objects, you need to override the GetHashCode
and Equals
methods.
Remove an item from a cache
To remove an item from a cache, use the Remove
method:
cache.Remove("key");
Clear a cache
To clear a cache, use the Clear
method:
cache.Clear();