In-Memory Caching in Xamarin

Caching in mobile apps is sometimes necessary, to help speed up your app from continuous requests for the same resources, or help alleviate issues due to poor network speed. Caching is a little more complex than just providing a store for values. You want to remove items from your cache when they expire and even remove items if your app comes under memory pressure.

This post only shows you how to keep In-Memory Cache. If you need persistent cache, cache that persists when the app shuts down then starts again, you might want to look at Akavache or MonkeyCache.


You will need to:

  • Use .NET Standard 2.0 for the latest version, otherwise you can use older version with older versions of .NET Standard
  • You must install Microsoft.Extensions.Caching.Memory in your Platform and Class Library project.


I would recommend injecting this into your IoC container, and having your Dependency injection framework make this available to your app. As an example on how to create a new instance, here is how you construct a new MemoryCache.

private readonly IMemoryCache _cache;

public CacheProvider()
    _cache = new MemoryCache(new MemoryCacheOptions() { });

In MemoryCacheOptions, you can have SizeLimits, how often to check the cache for items that have expired, and compression when under memory pressure. You can change these to suit your requirements.

Using Caching


To add something to the cache, you can use this method.

public void Set<T>(string key, T value, DateTimeOffset absoluteExpiry)
    _cache.Set(key, value, absoluteExpiry);

There are more options you can play around with, if this doesn’t fit your exact needs.


To retrieve an item from the cache, you can use this method.

public T Get<T>(string key)
    if (_cache.TryGetValue(key, out T value))
        return value;
        return default(T);


In-Memory caching is very easy with Microsoft’s Caching Extension. It is normally used in ASP.NET Core, but the fantastic thing about .NET Standard, is its ability to be used on any supported platform.