Using Memory Cache to Improve Performance in ASP.NET Core

Using Memory Cache to Improve Performance in ASP.NET Core

Caching is one of the most useful techniques to increase the speed of response of an application, in this case we will be talking about how to use this functionality in your web application developed in ASP .NET Core and you will learn what are the advantages and that you should Take into account you are using memory cache.

When to Use Memory in Cache?

We can use the cache memory in our favor when we have resources in our application that are constantly consulted and their information does not have much variation.

Note: This last point is very important, if the data that we consult changes frequently instead of improving, we can affect the performance of the application sample, causing more information to accumulate in the server’s memory.

To make it clearer when using memory, keep in mind the following rules:

  • The cached memory should allow the information to be returned faster than by consulting the original source.
  • Your application must always be able to consult its resources without having a total dependency on memory storage.
  • Memory storage is limited and must be pending:
    • Specify expiration time of the cache memory.
    • Do not use external inputs to indicate the cache key.

Bien, dicho lo anterior comenzamos…

Now if: How to Improve Performance with App Memory Cache in .Net Core?

Starting to use memory in cache with .NET Core is quite simple, to add this service we should only reference in our ConfigureServices by calling the extension method AddMemoryCache.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;

public class Startup
    public void ConfigureServices(IServiceCollection services)


    public void Configure(IApplicationBuilder app)

This will allow us to use the IMemoryCache class through dependency injection and now in our constructor we can do the following:

public class HomeController : Controller
    private IMemoryCache _cache;

    public HomeController(IMemoryCache memoryCache)
        _cache = memoryCache;

Examples 1: Store Memory Information

Now that you have an instance in your controller you can store information using the Set method which receives a key, an object to store and some options for the cache with the MemoryCaheEntryOptions class that we will explain later:

_cache.Set("my_object_in_cache",myObject, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(3)));

In the previous code we can see that the variable myObject is the object that you want to store and we pass an instance of MemoryCacheEntryOptions with the cache options indicating an expiration time of 3 minutes.

Within the cache options we can also set:

  • SlidingSize: time that the object can last without being accessed and not being removed.
  • Priority: priority that the object has to be maintained when the application has to clean the memory.
  • PostEvictionCallbacks: accepts a reference to a method that will be called when the object is cleaned in memory.
  • Size: size that the object can have in memory.

You can see all the options here: MemoryCacheEntryOptions

Example 2. Obtain Object in Memory Cache

To consult an object that has memory we use the method Get which receives a key and returns null when it has no results. Note that you can set the type of object you want to return.

var objectInMemory = _cache.Get<ObjectType>("my_object_in_cache");

You can also use the GetOrCreate method that allows you to verify if the object already exists and if it does not create a new record. See an example:

var objectInMemory = _cache.GetOrCreate(myObject,"my_object_in_cache", options);

Example 3. Move Object in Memory

To remove an object in cache memory you can use the Remove method that receives the key of the object in memory. See an example:



As I mentioned earlier, the cache in memory is a bit limited, you can use it more depending on the capacity of the server where you have your application hosted.

That said, I understand this is its main disadvantage or limiting because you must be very careful with the objects and the time they last in memory so that your application does not collapse.

My recommendation is that you use it with small calls to your application that are frequent and that the data does not change that much, but storing a small amount of information.

If you need to store large objects that require more capacity then it is advisable to use a distributed cache server that offers you more capacity for these purposes.

I hope you have been helped with the content and let me know in the comments box your opinion.

Leave a Comment