Thursday, July 18, 2024

Caching Strategies in .NET Core 8.0

Caching is a technique used to store frequently accessed data in memory, so future requests for that data can be served faster. In .NET Core 8.0, there are several caching strategies that you can use to optimize your applications. Let’s explore some of them.

1. In-Memory Caching

In-memory caching stores data in the memory of the web server. It’s fast and easy to implement. Here’s an example:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMemoryCache();
    }
}

public class MyController : Controller
{
    private IMemoryCache _cache;

    public MyController(IMemoryCache memoryCache)
    {
        _cache = memoryCache;
    }

    public IActionResult Index()
    {
        DateTime cacheEntry;

        if (!_cache.TryGetValue("MyKey", out cacheEntry))
        {
            cacheEntry = DateTime.Now;

            var cacheEntryOptions = new MemoryCacheEntryOptions()
                .SetSlidingExpiration(TimeSpan.FromSeconds(60));

            _cache.Set("MyKey", cacheEntry, cacheEntryOptions);
        }

        return View(cacheEntry);
    }
}

2. Distributed Caching

Distributed caching involves storing data across multiple nodes, typically in a cache cluster. This is useful for web farm scenarios where you have multiple web servers. Here’s how you can use it:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddStackExchangeRedisCache(options =>
        {
            options.Configuration = "localhost";
            options.InstanceName = "SampleInstance";
        });
    }
}

public class MyController : Controller
{
    private IDistributedCache _cache;

    public MyController(IDistributedCache distributedCache)
    {
        _cache = distributedCache;
    }

    public async Task<IActionResult> Index()
    {
        var cacheKey = "TheTime";
        var existingTime = _cache.GetString(cacheKey);

        if (existingTime == null)
        {
            existingTime = DateTime.UtcNow.ToString();
            _cache.SetString(cacheKey, existingTime);
        }

        return View(existingTime);
    }
}

3. Response Caching

Response caching adds cache-related headers to responses. Browsers and proxy servers use these headers to store responses. Here’s an example:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddResponseCaching();
    }
}

[ResponseCache(Duration = 60)]
public class MyController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

Remember, each caching strategy has its own use cases and trade-offs. Choose the one that best fits your application’s needs. Happy coding!