Skip to content

Custom cache

Joakim Skoog edited this page Jun 11, 2017 · 4 revisions

Configuration with a custom cache

This page will teach you how to use Cashew if you're not interested in also using CacheManager. Maybe you have another cache solution in place or you just want to implement your own, this is where you will find all information that's needed.

The main interface in Cashew is IHttpCache and that's the one you will need to implement.

/// <summary>
/// The contract for caching functionality that is used for caching HTTP responses.
/// </summary>
public interface IHttpCache : IDisposable
{
    /// <summary>
    /// Retrieves the value associated with the given key from the cache.
    /// </summary>
    /// <param name="key">The key that is used to identify the value in the cache.</param>
    /// <returns>The value in the cache that is associated with the given key.</returns>
    /// <exception cref="T:System.ArgumentNullException">If the <paramref name="key"/> is null</exception>
    object Get(string key);

    /// <summary>
    /// Removes the value associated with the given key from the cache.
    /// </summary>
    /// <param name="key">The key that is used to identify the value in the cache.</param>
    void Remove(string key);

    /// <summary>
    /// Puts a value associated with the given key into the cache.
    /// </summary>
    /// <param name="key">The key that is used to identify the value in the cache.</param>
    /// <param name="value">The value which should be cached associated with the given key.</param>
    /// <exception cref="T:System.ArgumentNullException">If the <paramref name="key"/> or <paramref name="value"/> is null.</exception>
    void Put(string key, object value);
}

Lets say we don't wany any fancy caching solutions and just need a simple dictionary. We can then implement IHttpCache in the following way:

public class DictionaryCache : IHttpCache
{
    private readonly ConcurrentDictionary<string,object> _cache = new ConcurrentDictionary<string, object>();
        
    public object Get(string key)
    {
        if (_cache.TryGetValue(key, out object value))
        {
            return value;
        }

        return null;
    }

    public void Remove(string key)
    {
        _cache.TryRemove(key, out object value);
    }

    public void Put(string key, object value)
    {
        _cache.AddOrUpdate(key, value, (oldKey, oldValue) => value);
    }

    public void Dispose()
    {
        _cache.Clear();
    }
}

After we've got our implementation we can pass it to the HttpCachingHandler constructor as usual and we're good to go!

//Create our cache with a backing dictionary
var simpleCache = new DictionaryCache();

//We want to use the standard key strategy
var keyStrategy = new HttpStandardKeyStrategy(simpleCache);

//Pass our cache into the HttpCachingHandler and we're good to go!
var httpCachingHandler = new HttpCachingHandler(simpleCache, keyStrategy);