In-memory caching in Asp.Net Core

As you know we use cache to improve performance as well as reduce the DB connections. You can use either the in-memory cache or distributed cache.

However, if you work on a project based on monolithic architecture, you should use in-memory caching.

In-memory caching is so easy to use and also it is effective in terms of your application performance.

Let’s get started and create a web application. Go to the visual studio (I use visual studio) and create a Web API app application.

Select ASP.NET Core Web API and click on the Next button

Fill in the details and click on the Next button

Keep it as it is and hit the Create button

After you create a project, you need to install Microsoft.Extensions.Caching.Memory package which is why right-click on your solution and select Manage NuGet Packages

Search for Microsoft.Extension.Caching.Memory and hit the Install button.

After you install the package, go to the program.cs and add the AddMemoryCache()

Go to the controller and update the controller to have the caching mechanism.

Inject IMemoryCache in the controller.

Create a HttpGet Method and implement a cache in it.

When you try it the first time, you will see method will call the FakeDbConnection method because the cache is empty. However, if you check it the second time, you will see that cache will return the value and the code will go to return Ok(result) directly.

Besides, TryGetValueto is used to check to see if the value is present in the cache or not. If it is present, the method will return the value otherwise, it will connect to the FakeDbConnection method.

InMemoryTestController.cs

This is how caching mechanism works and improves the performance.

You can define cache entry options before you set the cache value if you want to.

InMemoryTestController.cs

Basically, you have to send the key and get the value once you want to use the cache. Do not forget that you can store variables, models, and so on not only string values.

Note that distributed cache works with the same logic only you need to install docker on your machine and create a container for caching mechanism. We will investigate the distributed caching mechanism in another article.

API: https://github.com/frttnk/In-memory-caching-in-Asp.Net-Core-6

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Firat

I am a Senior Full-Stack .Net Developer who is trying to share hands-on experience and other technologies that are related to Full-stack development.