C# MemoryCache Tagging

Petr Kostelanský | 15 November 2017
Sometimes we need to remove all cache objects that contains specific entity because this entity has changed. We can do that by tagging and I will show you how.

I was looking for something like this but I could not find any cache library that will support tagging so I have created one.

MemoryCache in C# basically doesn't support tagging so I had to create wrapper for it. 

Why is tagging needed

Imagine that you cache for example products. You have product with Id 1 that has Name, Description, Price etc. This Product can be cached with different keys at the same time. For example you can cache this product separately with key product-detail-1 and also this product can be in collection of products under key the-most-popular-products. But when you update this product and change for example price of product you want remove this product from all cached objects. So you have to remove product-detail-1 and also the-most-popular-products objects from cache because both contains product with Id 1. And this the situation where tagging help you because you will have the information in which cached objects is contained our product.

How use it

Let's look at same examples how use it:

At first we have to create enum that will represent our tags

public enum Entities
{
    Product,
    Article,
    Category
}

Than we create our product object and cache manager

var product = new Product
{
    Id = 10,
    Name = "My Product 10",
    Price = 25
};

var cache = new CacheManager();

Now we can call SetValue and pass enum item parameter into. Entities.Product is tag that will mark our cache object. new int[] { 10 } is array that represents ids of products contain in cached object. Our cached object will contains product with id 10 for now.

string key = "product-detail-1";
cache.SetValue(key, product, 1, Entities.Product, new int[] { 10 });

We can also cached collection of object:

string key = "the-most-popular-products";
cache.SetValue(key, productCollection, 1, Entities.Product, new int[] { 10, 11, 15, 20 });

Now, we will change price of product with id 10 and we will need to remove this object from cache. We of course need to remove all cached objects that contains product with id 10

cache.RemoveByTags(Entities.Product, 10);

 

Download:

MemoryCache-Tagging library is possible to download from github.
Library is in .NET Standard and you can use it in .NET Core app and also in .NET Framework app.

If you want to use it in .NET Framework app you have to do one small change in your project:
Open up the .csproj file for the Framework project and add this line within the first <PropertyGroup> like this to change the restore style:

<RestoreProjectStyle>PackageReference</RestoreProjectStyle>

Explanation find here Referencing .NET Standard Assemblies from both .NET Core and .NET Framework

Loading ads...