10 things to know about In-Memory Caching in ASP.NET Core

Tram Ho

The main purpose of any caching mechanism is to improve the performance of the application. As an ASP.NET developer you probably know about web forms, ASP.NET MVC may also have used the Cache object to cache application data. This is often referred to as server-side data caching and is a feature available in the framework. Although ASP.NET Core does not have such a Cache object, you can implement in-memory caching quite easily. This article guides you on how to do it.

Before going any further you need to create a new ASP.NET application based on the Web Application project template. You choose as shown below:

Next, the steps below cover step by step, step by step, to build and test features proposed by in-momory caching.

1. Enable In-memory caching in the Startup class

Unlike ASP.NET web forms and ASP.NET MVC, ASP.NET Core doesn’t have a built-in Cache Object that you can use directly inside the Controller . Here, in-memory caching works through dependency injection and the first step is to register the in-memory caching service in the Startup class. So, open this class and put the code in the ConfigureServices() . Edit the ConfigureServices() as shown below:

To be able to use in-memory caching in your application, you need to call the AddMemoryCache() in the service collection. This is the default implementation of an in-memory cache – an IMemoryCache object – that can be IMemoryCache to controllers.

2. In-memory caching uses dependency injection to inject the cache object

Next, open HomeController and edit it like the code below:

As you can see, the above code declares a private variable of ImemoryCache . This is the variable assigned in the constructor. Constructor gets the cache parameter through DI, then this cache object is stored in local variable for later use.

3. Use the Set () method to store an item in the cache

Once you have an IMemoryCache object you can read and write data with it. Adding an entry to the cache is pretty straightforward and straightforward.

The above code sets a cached data in the Index() action. This is done by using the Set<T>() of the IMemoryCache object. The first parameter to the method is a key that identifies the cache. The second parameter is the value of the key. In this example we store a key and value as a string, but you can also store it with other data types (built-in and built-in types).

4. Use the Get() to retrieve an item from the cache

After you add data to the cache, you desire to receive them somewhere in the application. You do this using the Get() . Use the code below.

The above code receives data from the cache at another action ( Show() ) of the HomeController . The Get() specifies the type of item and its key. We try to display the data retrieved from the cache, here it is a timestamp.

Try to open page / Home / Show, see the results as shown:

5. Use TryGet() to check for existence of the key

If you look at the previous example, you will find that every time you navigate to /Home/Index , a new timestamp is assigned to the cache item. This is because we do not give any check if the key already exists or not before assigning the value. There are two ways to do that inside the Index() action. Please observe both as the code below:

The first method is the same as the Get() you used earlier. However, this time it uses the if block.

The second one looks cleaner. It uses the TryGet() to receive an item. This method returns boolean type. True if the key already exists in the cache, False otherwise. The advantage of this approach is that the value of the cache is given an out parameter for later use. That way it is possible to both check the existence and get the value in the same method.

6. Use GetOrCreate() to add an item if it doesn’t already exist

Sometimes you need to get an existing item from the cache and if the item doesn’t already exist then you want to add it. This makes the code more concise. With the same line of code, you can both get values ​​and add new ones if you don’t already exist, helping to reduce the existence check.

7. Set your timeout by absolute time and unused time

In the previous example, an item cache when added is retained in the cache unless it is removed using the Remove() . You can also set an absolute and relative time on an item cache. An absolute timeframe means that the cached item will be removed at an apparent time and date. The relative time here is that the cache will be removed after a certain amount of time (no access).

To set this expiration time use the MemoryCacheEntryOptions object. The code below is how to set it up:

AbsoluteExpiration above indicates that the cache will expire 2 minutes from the current point in time regardless of whether the cache is accessed or not. And SlidingExpiration will decide the cache will expire after 1 minute if it is not accessed even if it still has AbsoluteExpiration ‘s term.

8. Can use callbacks when the items in the cache are removed

There may be times when you want to report whenever the data in the cache is removed. For example, an item removed by calling the Remove() , can also be removed due to expiration due to the AbsoluteExpiration or SlidingExpiration . Then, we need to set up the RegisterPostEvictionCallback option as below:

In the above example, the function callback name is MyCallback . The second argument is a state object, you will pass it to the functon call back. Here we pass the instance of HomeController .

The MyCallback function looks like below:

Observe this code carefully. MyCallback() is a private static function inside the HomeController . It has 4 parameters. The first two parameters are the key and value of the item that has just been cleared from the cache. The third parameter specifies the reason why the item was removed. EvictionReason is an enumeration and lists various reasons such as: Expired , Removed, and Replaced .

Inside the callback we simply save the content of the message talking about the cause of the removal. This message is also stored in the cache.

Next, we will display this message on the UI as below code:

Action Show() :

html:

Run the application:

9. Set the priority for the item to be cached

Just as you can set a cache expiration policy, you can also set its priority. If the server has limited memory, then this priority determines which items will be deleted in order to regain memory. To set the priority you use MemoryCacheEntryOptions again.

CacheItemPriority is an enum, it has four priorities include: Low, Normal, High and NeverRemove Based on the priority on the cache will be deleted from the item with a low priority to high, individual NeverRemove will not be deleted for any reason.

10. Can establish a dependency between multiple item caches

You can also set a dependency between the item cache so that when an item is deleted all dependent items are also deleted with it. To see how it works, edit the Index() action like the code below:

The code starts by creating a CancellationTokenSource object and the object is stored as a cts independent cache item. Next, MemoryCacheEntryOptions is created as before. Then the AddExpirationToken() is called to specify an expiration token. If the token is active, the item remains in the cache, and if the token is destroyed, the item will also be removed from the cache. After the item is removed from the cache, MyCallback will be called as mentioned in the previous section. Next the code creates 2 more items (key1 and key2). While creating these two items, the third parameter to be passed is a CancellationChangeToken created earlier.

That means we have 3 keys: timestamp is the primary key, key1 and key2 are dependent on timestamp . When the timestamp is deleted, key1 and key2 also deleted. You can do it like the code below:

To test the results, you run the following urls in turn: /Home/Index , /Home/Show , /Home/Remove

11. Conclusion

The use of the cache is always necessary for any web application, as well as any language. So, with the detailed and clear instructions in the article hopefully will help the beginners to quickly grasp cache grasping. Thank you for watching the article.

Posts translated from source:

10 Things To Know About In-Memory Caching In ASP.NET Core

Share the news now

Source : Viblo