Day 16 of 30-Day .NET Challenge: In-Memory Caching
Tags: dotnet, csharp, beginners, programming
Published: 2024-04-04 07:09:00

Challenges are hard when the database resides in a remote machine or experiencing heavy load. The in-memory caching acts as a better implementation to avoid performance bottlenecks.


## Introduction

One of the major issues in an application's performance is the time it takes to respond from external data sources mostly databases. Challenges are hard when the database resides in a remote machine or experiencing heavy load. The in-memory caching acts as a better implementation to avoid performance bottlenecks.

### Learning Objectives

* How to use in-memory caching

* Key benefits

### Prerequisites for Developers

* Basic understanding of C# programming language.

[30 Day .Net Challenge](https://singhsukhpinder.medium.com/list/52a751260fe1)

## Getting Started

Usually, developers directly fetch information or data directly from the database. It is quite straightforward and simple approach but can lead to performance issues when the database is under a heavy load which impacts application performance and hampers UI experience
```csharp
    public Product GetProductById(int id)
    {
        // Fetching product data from the database every time
        var product = _dbContext.Products.FirstOrDefault(p => p.Id == id);
        return product;
    }
```
### How to implement in-memory caching

In-memory caching involves temporarily storing frequently accessed data in the memory of the application server, drastically reducing the need to retrieve data from the database for each request.
```csharp
    private static MemoryCache _cache = new MemoryCache(new MemoryCacheOptions());
    
    public Product GetProductById(int id)
    {
        // Fetching product data from the cache if available
        if (!_cache.TryGetValue(id, out Product product))
        {
            product = _dbContext.Products.FirstOrDefault(p => p.Id == id);
            _cache.Set(id, product, TimeSpan.FromMinutes(30));
        }
        return product;
    }
```
To use MemoryCache, you need to add the Microsoft.Extensions.Caching.Memory package to your project.
```csharp
    dotnet add package Microsoft.Extensions.Caching.Memory
```
Create a class InMemoryCache with function named GetProductById which returns a class object of type Product
```csharp
    public static class InMemoryCache
    {
        private static MemoryCache _cache = new MemoryCache(new MemoryCacheOptions());
        private static ProductRepository _productRepository = new ProductRepository();
        public static Product GetProductById(int id)
        {
            if (!_cache.TryGetValue(id, out Product product))
            {
                Console.WriteLine("Fetching from database...");
                product = _productRepository.GetProductById(id);
                _cache.Set(id, product, TimeSpan.FromMinutes(30)); // Cache for 30 minutes
            }
            else
            {
                Console.WriteLine("Fetching from cache...");
            }
    
            return product;
        }
    }
```
Simulate the ProductRepository and relevant Product class
```csharp
    // Simulating a product repository
    public class ProductRepository
    {
        public Product GetProductById(int id)
        {
            // Simulate database access
            return new Product { Id = id, Name = $"Product {id}" };
        }
    }
    
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
```
Call from the main method as follows and relevant console output showcasing data fetched from memory.
```csharp
    #region Day 16: In-Memory Cache
    
    Console.WriteLine("Fetching product with ID 1 for the first time:");
    var product = InMemoryCache.GetProductById(1);
    Console.WriteLine($"Product Name: {product.Name}\n");
    
    Console.WriteLine("Fetching product with ID 1 again:");
    product = InMemoryCache.GetProductById(1); // This time, it should come from the cache
    Console.WriteLine($"Product Name: {product.Name}\n");
    
    #endregion
```
![](https://cdn-images-1.medium.com/max/2000/1*dPbCp7hGGcZ3lKs_R8cy3w.png)

### Key Benefits

* Reduce database load

* Improved application performance

* Scalability

## Complete Code on GitHub
[GitHub — ssukhpinder/30DayChallenge.Net](https://github.com/ssukhpinder/30DayChallenge.Net/tree/main)

### C# Programming🚀

Thank you for being a part of the C# community! Before you leave:

Follow us: [Youtube](https://www.youtube.com/channel/UCejYGg4gAOa1uPAObFuk1HQ) | [X](https://twitter.com/sukhsukhpinder) | [LinkedIn](https://www.linkedin.com/in/sukhpinder-singh/) | [Dev.to](https://dev.to/ssukhpinder) 
Visit our other platforms: [GitHub](https://github.com/ssukhpinder) 
More content at [C# Programming](https://medium.com/c-sharp-progarmming)