SimpleObjectCache is a very simple permanent, cross-platform, asynchronous key-value object cache for .NET. It comes with built-in SQLite 3 support. Alternative backends can be added by implementing the IObjectCache or IBulkObjectCache interfaces.

How it works

First, you need to set the ApplicatioName. This is also going to be the folder where your cache will reside. Depending on the host OS the location of this folder might be different. On Windows it would be something like C:\ProgramData\<ApplicationName>\SimpleObjectCache.

Let’s instantiate SimpleObjectCache so we can use it:

Now we create a Person, then store it into our cache.

As we insert an object into the cache we can also set its expiration date:

Inserting an object with an already existing key, which we just did, will overwrite the previous object with the same key. Retrieving the object is a matter of providing its key:

To remove the object from the cache we use the Invalidate method:

Bulk inserts are also possible:

Note that we just set the Tom and Mike expiration date to yesterday. Now let’s add John again. For him however, we set an expiration date which is bigger than Tom’s and Mike’s:

The Vacuum method removes expired objects from the cache. So Tom and Mike, whose dates are passed, are going to be purged by the following command:

Now let’s get all the available Person objects from the cache.

Since Tom and Mike are gone, we only got one object back, and that’s our very own little John.

Installation

SimpleObjectCache is on NuGet. Run the following command on the Package Manager Console:

Or install via the NuGet Package Manager in Visual Studio.

Wrapping it up

We needed a simple cache that we could use as a component of our cross-platform storage system (more on that in a future post). We wanted the cache to also run seamlessly on the old .NET 4.0 framework. Unfortunately Akavache, to which this project is blatantly inspired, does not run on .NET4, so I decided to roll out my own simplified alternative. This project also offered a great occasion get my feet wet with bait-and-switch portable classes and a few other interesting challenges.

Currently supported platforms are iOS and Android (Xamarin) and .NET Framework versions 4.0 and .NET 4.5+.

If you want to get in touch, I am @nicolaiarocci on Twitter.