Skip to content

Instantly share code, notes, and snippets.

@jdylanmc
Last active July 27, 2020 21:18
Show Gist options
  • Save jdylanmc/4872338538665f8d35eb66b0f9cb911f to your computer and use it in GitHub Desktop.
Save jdylanmc/4872338538665f8d35eb66b0f9cb911f to your computer and use it in GitHub Desktop.
Example of leveraging Sitecore Caching engine in custom code
public class CacheService
{
private const string CacheName = "Custom_Cache"; // a unique name for your cache
private readonly ICache<string> _cache;
public CacheService()
{
_cache = CacheManager.FindCacheByName<string>(CacheName);
if (_cache != null) // if cache is already initialized, return out
return;
// else create a new cache
_cache = new Cache<string>(CacheName, Sitecore.Configuration.Settings.Caching.DefaultFilteredItemsCacheSize)
{
Enabled = true,
Scavengable = false
};
}
public void AddToCache(string key, object data, DateTime absoluteExpiration)
{
if (!_cache.ContainsKey(key))
{
_cache.Add(key, data, absoluteExpiration);
}
}
public object GetFromCache(string key)
{
return _cache?.GetValue(key);
}
// this method can be called from a publish:end event handler to wipe your caches
public void Clear(object sender, EventArgs args)
{
_cache.Clear();
}
}
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:set="http://www.sitecore.net/xmlconfig/set/">
<sitecore>
<events>
<!-- clear custom cache when publishing completes -->
<event name="publish:end">
<handler type="MySite.Services.CacheService, MySite.Services" method="Clear" />
</event>
<event name="publish:end:remote">
<handler type="MySite.Services.CacheService, MySite.Services" method="Clear" />
</event>
</events>
</sitecore>
</configuration>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment