Creating a cache

Version: 9.3

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 static CacheManger class:

    RequestResponse
    ICache<string> cache = CacheManager.GetNamedInstance("global_cached_items", 1024, true);
  • Use dependency injection:

    RequestResponse
    LazyResetable<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:

RequestResponse
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:

RequestResponse
cache.Add("key", "value");    
Note

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:

RequestResponse
object result = cache.GetValue("key");
Note

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:

RequestResponse
cache.Remove("key");

Clear a cache

To clear a cache, use the Clear method:

RequestResponse
cache.Clear();

Do you have some feedback for us?

If you have suggestions for improving this article,