Caching in ASP.NET Core using MemoryCache

Quality Thought: The Best Full Stack .NET Training Institute in Hyderabad with Live Internship Program

In today's rapidly evolving tech industry, becoming proficient in Full Stack development is more essential than ever. With a myriad of technologies to learn, it's crucial to have expert guidance and hands-on experience. That’s where Quality Thought stands out as the premier choice for aspiring developers. As one of the best Full Stack .NET training institutes in Hyderabad, Quality Thought offers an industry-focused curriculum and a unique Live Internship program designed to provide students with real-world experience.

Why Choose Quality Thoughts for Full Stack .NET Training?

Comprehensive Curriculum: Covers front-end, back-end, database, cloud integration, and deployment.

Industry Experts as Trainers: Learn from professionals working on real-time .NET projects.

Live Internship Program: Work on real-time client projects and gain hands-on experience.

Career Support: Resume preparation, mock interviews, and placement assistance.

Flexible Batches: Weekend and weekday options available for working professionals and career-switchers.

Caching in ASP.NET Core using MemoryCache

Caching is a powerful technique to improve performance and reduce server load by storing frequently accessed data in memory. In ASP.NET Core, one of the most commonly used caching mechanisms is MemoryCache.

MemoryCache is a part of Microsoft.Extensions.Caching.Memory and stores data in the server’s memory. It’s ideal for small-to-medium data that is frequently accessed but not shared across servers (non-distributed).

To use MemoryCache, first register it in your Startup.cs (for .NET 5 or earlier) or in the Program.cs file (for .NET 6+):

csharp

builder.Services.AddMemoryCache();

Next, inject IMemoryCache into your service or controller:

csharp

public class ProductService

{

    private readonly IMemoryCache _cache;

    public ProductService(IMemoryCache cache)

    {

        _cache = cache;

    }

    public Product GetProductById(int id)

    {

        string cacheKey = $"product_{id}";

        if (!_cache.TryGetValue(cacheKey, out Product product))

        {

            product = FetchProductFromDatabase(id); // Simulate DB call

            var cacheEntryOptions = new MemoryCacheEntryOptions()

                .SetSlidingExpiration(TimeSpan.FromMinutes(10))

                .SetAbsoluteExpiration(TimeSpan.FromHours(1));

            _cache.Set(cacheKey, product, cacheEntryOptions);

        }


        return product;

    }

}

Here, TryGetValue checks if the data is in the cache. If not, it retrieves it from the database and stores it in the cache with expiration settings.

MemoryCache is easy to use and efficient for single-server applications. However, for distributed environments, consider using DistributedCache or external cache providers like Redis.

Read More

Rate Limiting in .NET Core APIs

Configuration in ASP.NET Core Apps

Logging in .NET Core with Serilog

Role-based Access Control in ASP.NET

JWT Authentication in .NET 7

Visit Our "Quality Thought" Training Institute in Hyderabad.

Comments