Popular Posts

June 27, 2024

How do you implement caching in ASP.NET Core

 

 Caching in ASP.NET Core can significantly improve application performance by storing frequently accessed data in memory. ASP.NET Core provides several options for implementing caching, ranging from simple in-memory caching to distributed caching across multiple servers. Here’s how you can implement caching in ASP.NET Core:

1. In-Memory Caching

In-memory caching is suitable for scenarios where cached data is used within a single instance of the application. It's simple to set up and does not require additional services.

Enable and Use In-Memory Caching

First, add the caching services in Startup.cs:

public void ConfigureServices(IServiceCollection services)

{

    services.AddControllersWithViews();


    // Add in-memory caching

    services.AddMemoryCache();

}


Next, use the cache in your controller or service:

using Microsoft.Extensions.Caching.Memory;


public class MyController : Controller

{

    private readonly IMemoryCache _cache;


    public MyController(IMemoryCache memoryCache)

    {

        _cache = memoryCache;

    }


    public IActionResult Index()

    {

        string cachedData;

        if (!_cache.TryGetValue("CachedDataKey", out cachedData))

        {

            // Key not in cache, so get data and set cache entry

            cachedData = GetDataFromDataSource();

            _cache.Set("CachedDataKey", cachedData, TimeSpan.FromMinutes(10)); // Cache for 10 minutes

        }


        return View(cachedData);

    }


    private string GetDataFromDataSource()

    {

        // Simulate getting data from a data source

        return "Cached data from data source";

    }

}

2. Distributed Caching (using Redis, SQL Server, etc.)

Distributed caching is suitable for scenarios where cached data needs to be shared across multiple instances of the application or multiple servers. ASP.NET Core supports various distributed cache providers like Redis, SQL Server, and others.

Use Redis for Distributed Caching

To use Redis for caching, you need to install the Microsoft.Extensions.Caching.StackExchangeRedis package and configure it in Startup.cs.


public void ConfigureServices(IServiceCollection services)

{

    services.AddControllersWithViews();


    // Add Redis distributed caching

    services.AddStackExchangeRedisCache(options =>

    {

        options.Configuration = "localhost:6379"; // Replace with your Redis connection string

        options.InstanceName = "SampleInstance"; // Optional: Redis instance name

    });

}

How do you implement caching in ASP.NET Core


Use Distributed Cache in Controller

using Microsoft.Extensions.Caching.Distributed;


public class MyController : Controller

{

    private readonly IDistributedCache _cache;


    public MyController(IDistributedCache distributedCache)

    {

        _cache = distributedCache;

    }


    public async Task<IActionResult> Index()

    {

        string cachedData;

        byte[] cachedBytes = await _cache.GetAsync("CachedDataKey");


        if (cachedBytes == null)

        {

            // Key not in cache, so get data and set cache entry

            cachedData = GetDataFromDataSource();

            cachedBytes = Encoding.UTF8.GetBytes(cachedData);

            var options = new DistributedCacheEntryOptions

            {

                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) // Cache for 10 minutes

            };

            await _cache.SetAsync("CachedDataKey", cachedBytes, options);

        }

        else

        {

            cachedData = Encoding.UTF8.GetString(cachedBytes);

        }


        return View(cachedData);

    }


    private string GetDataFromDataSource()

    {

        // Simulate getting data from a data source

        return "Cached data from data source";

    }

}

3. Response Caching (for HTTP Responses)

ASP.NET Core also supports response caching to cache the output of HTTP responses, which is useful for caching entire pages or API responses.

Enable Response Caching


public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    // Enable response caching
    services.AddResponseCaching();
}


Use Response Caching in Controller


[ResponseCache(Duration = 60)] // Cache for 60 seconds
public IActionResult Index()
{
    return View();
}


Summary

Implementing caching in ASP.NET Core involves configuring caching services (IMemoryCache, IDistributedCache, or ResponseCache) in Startup.cs and using them appropriately in your controllers or services. The choice between in-memory caching and distributed caching depends on your application’s scalability and performance requirements.

No comments:
Write comments