In-Memory Caching in ASP.NET Core-Basic guide of Caching

In-Memory Caching in ASP.NET Core-Basic guide of Caching

In this article we will discuss about in depth about In-Memory Caching in ASP.Net Core. Here we discuss about all the possibilities of caching and will build a simple endpoint that can help demonstrate of cache entries from the in-memory Cache, and finally we will check after enabling the caching the application performance.

Find Source Code

Prerequisites

– Basic knowledge of Caching
– Visual Studio 2019
– .NET Core SDK 5.0 ( You can use SDK 3.1 )
In-Memory Caching in ASP.NET Core-Basic guide of Caching
Tweet

What is Caching ?

Caching is the process of storing copies of files in a cache, or temporary storage location, so that they can be accessed more quickly.

A cache is a hardware or software component that stores data so that future requests for that data can be served faster; the data stored in a cache might be the result of an earlier computation or a copy of data stored elsewhere. In simply we can say the most frequently used data are stored in a temporary storage so that it can be accessed much faster for the future calls from the client. This technique will boost the performance of the application drastically by removing unnecessary and frequent requests to the data source.

Caching can significantly improve the performance and scalability of an app by reducing the work required to generate content. Caching works best with data that changes infrequently and is expensive to generate. Caching makes a copy of data that can be returned much faster than from the source. Apps should be written and tested to never depend on cached data.

  • On left hand side, you can see every time the resources are called to the datasource that may burden to the server and counter performance issue.
  • Whereas on right side part, you can see when a user is call to a datasource then it cached and it provide the result set from cached datasource only not the main datasource, so from performance point of view it should be much faster.

Caching In ASP.NET Core

ASP.NET Core support for various types of caching as follows.

  1. In-Memory Caching – Where the data is cached within the server’s memory.
  2. Distributed caching – The data is stored external to the application in sources like Redis cache etc., we will discuss it later.

In-Memory Caching in ASP.NET Core ?

In ASP.NET Core, it is now possible to cache the data within the application, this is known as In-Memory Caching in ASP.NET Core. The simplest cache is based on the IMemoryCache. IMemoryCache represents a cache stored in the memory of the web server. Apps running on a server farm (multiple servers) should ensure sessions are sticky when using the in-memory cache. Sticky sessions ensure that subsequent requests from a client all go to the same server.

In-memory caching is a service that’s referenced from an app using Dependency Injection. So, we first need to register this service to the built-in IoC container of ASP.NET Core by modifying ConfigureServices method of Startup.cs.

Cache Implementation in ASP.NET Core application

We have created the ASP.NET Core web API application that have set up an API and configured Entity Framework Core. This API will return a list of all customers in the database. If you need to learn about setting up Entity Framework Core in ASP.NET Core, we recommend you to go through this article – CRUD Operation in ASP.NET Web API with Entity Framework.

In this example we created a ASP .NET Core web API 5.0 project and connect with EF along with customer database.

In-Memory Caching in ASP.NET Core is a Service that should be registered in the service container of the application.

services.AddMemoryCache();

The above line of code should be add on configure services. This adds a non-distributed, in-memory implementation to the IServiceCollection. Now our Application eligible to provide in-memory caching.

Implement Cache in Controller Endpoint

[Route("api/[controller]")]
    [ApiController]
    public class CustomersController : ControllerBase
    {
        private readonly ApplicationDbContext _context;
        private readonly IMemoryCache memoryCache;
        public CustomersController(ApplicationDbContext context, IMemoryCache memoryCache)
        {
            _context = context;
            this.memoryCache = memoryCache;
        }
        // GET: api/Customers
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Customer>>> GetCustomers()
        {
            var cacheKey = "Allcustomer";
            if (!memoryCache.TryGetValue(cacheKey, out List<Customer> customerList))
            {
                customerList = await _context.Customers.ToListAsync();
                var cacheExpiryOptions = new MemoryCacheEntryOptions
                {
                    AbsoluteExpiration = DateTime.Now.AddMinutes(5),
                    Priority = CacheItemPriority.High,
                    SlidingExpiration = TimeSpan.FromMinutes(2)
                };
                memoryCache.Set(cacheKey, customerList, cacheExpiryOptions);
            }
            return customerList;
        }
      }
  }

Code Explanation

  • Line #6 – IMemoryCache definition
  • Line #16 – Here we are setting the cache key internally in our code.
  • Line #17 – If there is a cache entry with the key as “Allcustomer”, then push this data to a List object. Else, if there is no such cache entry, call the database via the context object and set this value as a new cache entry along with the expiration parameters. The expiration date is according to you, you can according to your requirements.
  • SlidingExpiration: Gets or sets how long a cache entry can be inactive (e.g. not accessed) before it will be removed. This will not extend the entry lifetime beyond the absolute expiration (if set).
  • AbsoluteExpiration: Gets or sets an absolute expiration date for the cache entry.

A cached item set with a sliding expiration only is at risk of becoming stale. If it’s accessed more frequently than the sliding expiration interval, the item will never expire. Combine a sliding expiration with an absolute expiration to guarantee that the item expires once its absolute expiration time passes

Test the In-Memory Cache in Postman

Let’s open the postman tool and test the cache performance.

You can see when I call the customer API, it fetch around 50-60 records to take time 9391 ms.

In this call, we are directly calling the database, which may be slow depending on the traffic, connection status, size of the response, and so on. We have configured our API to parallelly store these records to the cache as well.

So in the second call, the response is expected at much more better time.

As you can see, on second API call it takes 39 ms. You can see the drastic improvement in the performance, this is how awesome Caching is.

Pros of In-Memory Cache

  • Much Quicker than other forms of distributed caching as it avoids communicating over a network.
  • Highly Reliable and best suited for Small to Mid Scale Applications.

Cons of In-Memory Cache

  • If configured incorrectly, it can consume your server’s resources.
  • With the scaling of application and longer caching periods, it can prove to be costly to maintain the server.
  • If deployed in the cloud, maintaining consistent caches can be difficult.

Points To Remember about Caching

  • Application should never depend on the Cached data as it is highly probable to be unavailable at any given time. Traditionally it should depend on your actual data source. Caching is just an enhancement that is to be used only if it is available/valid.
  • Try to restrict the growth of the cache in memory. This is crucial as Caching may take up your server resources if not configured properly. You can make use of the Size property to limit the cache used for entries.
  • Use Absolute Expiration / Sliding Expiration to make your application much faster and smarter. It also helps restricts cache memory usage.
  • Try to avoid external inputs as cache keys. Always set your keys in code.

How to improve Cache Entry

To do improvements on caching, we can use Background Jobs to update cache at a regular interval. If the Absolute Cache Expiration is set to 10 minutes, then we can can run a recurring job every 11 minutes of interval to update the cache entry. You can use Hangfire to achieve the same in ASP.NET Core Applications.

Find source code

Summary

In this detailed article, we have learnt about In-Memory Caching in ASP.Net Core. We discussed Caching, the Basics, In-Memory Caching, Implementing In-Memory Caching in ASP.NET Core etc.

That’s a wrap for this article. I hope that it cleared about In-Memory Caching in ASP.NET Core-Basic guide of Caching. Please write to us if have any.

Have you enjoyed this post and found it useful? If so, please consider supporting me:

Buy me a coffeeBuy me a coffee

Redis Caching in ASP.NET Core- Depth in Distributed Caching
Redis Caching in ASP.Net Core

This article explain about Redis Caching in ASP.NET Core, We discuss about Distributed Caching, Redis, Setting up Redis Caching in Read more

CQRS pattern with MediatR in ASP.NET Core 5.0
CQRS pattern with MediatR in ASP.NET Core 5.0

This article explain CQRS design pattern with MediatR in ASP.Net Core 5.0. CQRS is a design pattern that separated the Read more

ASP.NET Core Web API with MongoDB CRUD- Beginner’s Guide
ASP.NET CORE WEB API 5.0 MONGODB CRUD

This article explain CRUD operation using MongoDB in ASP.NET Core Web API. We discuss here basics of MongoDB and how Read more

Build CRUD REST APIs with ASP.NET Core 5.0 with EF Core 5.0
Build CRUD REST APIs with ASP.NET Core 5.0

This article explains how to build CRUD REST APIs with ASP.NET Core 5.0 with EF core 5.0 and API secured Read more

Running WordPress on ASP.NET Core with Peachpie

Running WordPress on ASP.NET Core with Peachpie

In this article we are going to discuss how to run WordPress on ASP.Net Core, without using PHP, or any source files on the server. It’s now possible to run an entire WordPress Application over an ASP.NET Core Host seamlessly, the following demonstration will show you how to add WordPress as a front-end to an existing ASP.NET Core application step by step.

Find Source Code

Prerequisites

VS 2019 / VS Code
.NET SDK 5.0 ( You can check with your version)
My SQL Server( WordPress will be using this Server to data persistence)

Running WordPress on NET Core

WordPress is a free, simplest, and most popular open-source content management system to create our own website or blog which is written in PHP and paired up with MySQL. WordPress on .Net Core is possible with peachpie, which is a compiler built on top of the Roslyn platform, it’s a set of runtime and base class libraries and everything that allows compiling a PHP project, a group of PHP files into a regular .Net project.

Peachpie allows for seamless both-way interoperability between PHP and .NET applications. In simpler terms, this means that one can have some parts of an application written in PHP, while other modules are written in .NET and everything will work together as one application. Here is the original Repository of the WordPress SDK by PeachPie. Without Peachpie, connecting these modules is tedious, time-consuming and often risky or producing unnecessary performance overhead.

Here are the following steps to run WordPress with ASP.Net Core.

Creating ASP.NET Core Project

Let’s Open Visual Studio and create a ASP.NET Core 5.0 Web project.

Installing the Required Package

As WordPress is already compiled to work on ASP.NET Core Applications. Thus all you have to do is to install the specified Package from Nuget. Open up your Package Manager Console and run the following snippet.

Install-Package PeachPied.WordPress.AspNetCore -Version 5.5.1-preview1

It might take a couple of minutes to install all the necessary packages, as the WordPress package itself is around 30Mb in file size.

After this package installation in the ASP.NET Core application you can find a new folder as WordPress with following information.

wordpress-in-aspnetcore-installed-wordpress

Set up the MySQL database

Now we need to set up the MySQL database. Make sure that we have the latest versions of both MySQL Server (Community) and MySQL Workbench installed on your machine. If not, download and install them from the below link.

https://dev.mysql.com/downloads/windows/installer/8.0.html

Open the MySQL Workbench and create a blank database/schema for our WordPress Application to run. The tables will be auto-generated by WordPress as soon as the application launches for the first time. Make sure you remember the username, password, database name, and the port at which MySQL is running. You need these details when we start configuring WordPress with ASP.NET Core.

To create a new database schema in MySQL server, Right click on sys and create schema. Then create the schema name, here we named as “wordpressdb” then click apply it should create the WordPressDB schema.

Make sure that you note down the username , password , database name and the port at which MySQL is running. We will need these details when we start configuring WordPress on ASP.NET Core

Configuring WordPress in ASP.NET Core

Let’s add the schema/database connection details into appsettings.json.

"wordpress": {
    "dbhost": "localhost",
    "dbpassword": "password",
    "dbuser": "root",
    "dbname": "wordpressdb"
  }

Now let’s open up the Startup.cs/ConfigureServices method and add in the following.

services.AddWordPress(options => { });

Next, in the Configure method, add the following.

 app.UseWordPress();

That’s it. We did all the setup of the application, build the application then run.

Click on Continue, then it navigate to another page where set the Title, username and password then Install WordPress.

After clicking on Install WordPress it successfully installed the WordPress then navigate to WordPress login like below and put the user credentials and then click on Login.

After successfully login you can now able to access the WordPress Dashboard.

Also you can see in the local database the required tables are updated and it captured the input details that we entered.

You can now open the site and can see the wordpress “Hello World”.

Benefits Of Running WordPress On ASP.NET Core

  • Performance: The compiled code is fast and also optimized by the .NET Just-in-Time Compiler for your actual system. Additionally, the .NET performance profiler may be used to resolve bottlenecks.
  • Source less Distribution: After the compilation, most of the source files are not needed. Peachpie compiles the entire source to DLLs which makes lives much easier.
  • C# Extensibility: You can implement plugins in a separate C# project and/or PHP plugins may use .NET libraries.
  • Secure: Peachpie allows the compiled WordPress clone to run in a .NET JIT , secure and manageable environment, updated through windows update.
  • Opens up the Hosting World to .NET Core Hosting Providers: Given the advantages of such an approach, people would now start hosting this variant of WordPress into .NET Hosts with ease which opens up a huge section of the market.

Source Code

Find Source Code

Summary

This article explained about Running WordPress on ASP.Net Core with Peachpie. We discussed here step by step how to integrate WordPress in ASP.Net Core application.

That’s a wrap for this article. I hope that it cleared about Running WordPress on ASP.NET Core with Peachpie. Please write to us if have any.

Have you enjoyed this post and found it useful? If so, please consider supporting me:

Buy me a coffeeBuy me a coffee

Toast Notifications in ASP.NET Core Razor Pages
Toast Notifications in ASP.NET Core Razor Pages

This article we will learn how simply we can use Toast Notifications in ASP.NET Core Razor Pages 5.0. Mainly on Read more

Integrate SMS in ASP.NET Core using Twilio
Integrate SMS in ASP.NET Core using Twilio

This article explain how to send an SMS with Twilio in ASP.Net Core using C#. So we will use Twilio Read more

Integrate Razorpay Payment Gateway in ASP.NET Core
Integrate Razorpay Payment Gateway in ASP.NET Core

This article explain about Integrate Razorpay Payment Gateway in ASP.NET Core. We discuss here how to implement Razorpay gateway in Read more

Deploy ASP.NET Core Web App in Azure Virtual Machine
Deploy ASP.NET Core Web App in Azure Virtual Machine

This article explain about Deploy ASP.NET Core Web App in Azure Virtual Machine. We discuss here how to create VM Read more

Pin It on Pinterest