How to use FusionCache in ASP.NET Core

By FoxLearn 1/5/2025 5:51:17 AM   17
FusionCache is an open-source hybrid caching solution for ASP.NET Core that combines in-memory and distributed caching while adding advanced features like adaptive caching, eager refresh, and in-memory synchronization.

Traditional .NET Core caching options (IMemoryCache, IDistributedCache, and the upcoming HybridCache in .NET 9) provide basic capabilities but may not meet all advanced needs. FusionCache addresses these gaps, offering enhanced performance and resiliency for applications.

What is FusionCache?

FusionCache is an open-source hybrid caching library known for its simplicity, speed, and robustness, with advanced resiliency features. Already utilized by Microsoft, it supports both in-memory (L1) and multi-level (L1 + L2) caching, where L2 can integrate any IDistributedCache implementation for sharing across servers.

Key features include:

  • L1 and L2 caching
  • Adaptive and conditional caching
  • Eager refresh
  • Cache stampede prevention
  • Synchronization
  • Fail-safe support

To use the FusionCache library, start by installing the ZiggyCreatures.FusionCache NuGet package in your project.

In Solution Explorer, right-click your project and select Manage NuGet Packages. Search for ZiggyCreatures.FusionCache in the NuGet Package Manager, then install it.

Alternatively, you can install the package using the NuGet Package Manager Console with the following command:

dotnet add package ZiggyCreatures.FusionCache

Configure FusionCache in ASP.NET Core

After installing FusionCache in your project, register it as a service in the Program.cs file. Once registered, you can configure it by adding the appropriate code snippet to the same file.

builder.Services.AddFusionCache(options =>
{
    options.DefaultEntryOptions = new FusionCacheEntryOptions
    {
        Duration = TimeSpan.FromMinutes(5),
        Priority = CacheItemPriority.High
    };
});

Create a new API controller in ASP.NET Core

To create a new API controller and implement FusionCache, follow these steps:

  1. In Solution Explorer, right-click on the project you created earlier and select the Controllers folder.
  2. Click Add New Item.
  3. Choose API Controller – Empty from the project template options.
  4. Provide a name for the API controller, such as OrderController.
  5. Click Add to finish the process.

This will generate a new API controller within the Controllers folder of your project.

Create an action method in the controller

Creating an action method in the OrderController class and implement FusionCache functionality.

[HttpGet("{orderId}")]
public async Task<IActionResult> GetOrderById(int orderId)
{
    var cacheKey = $"order_{orderId}";
    var cachedOrder = await _fusionCache.GetOrSetAsync(
        cacheKey, async () =>
        {
            return await _orderRepository.GetOrderById(orderId);
        },
        options => options.SetDuration(TimeSpan.FromMinutes(5)).SetFailSafe(true)
    );

    if (cachedOrder == null)
    {
        return NotFound();
    }
    return Ok(cachedOrder);
}

In this example, the GetOrderById action method retrieves an order by its ID. Using the GetOrSetAsync method from FusionCache, it first checks the cache for the data. If not found, it fetches the data from the database.

Use Constructor Injection for Repository and Cache

To use dependency injection, we inject instances of IOrderRepository and IFusionCache into the OrderController constructor, as shown below:

private readonly IOrderRepository _orderRepository;
private readonly IFusionCache _fusionCache;

public OrderController(IFusionCache fusionCache, IOrderRepository orderRepository)
{
    _fusionCache = fusionCache;
    _orderRepository = orderRepository;
}

Here’s the complete OrderController class with FusionCache integration:

using Microsoft.AspNetCore.Mvc;
using ZiggyCreatures.Caching.Fusion;

namespace FusionCacheExample.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OrderController : ControllerBase
    {
        private readonly IOrderRepository _orderRepository;
        private readonly IFusionCache _fusionCache;

        public OrderController(IFusionCache fusionCache, IOrderRepository orderRepository)
        {
            _fusionCache = fusionCache;
            _orderRepository = orderRepository;
        }

        [HttpGet("{orderId}")]
        public async Task<IActionResult> GetOrderById(int orderId)
        {
            var cacheKey = $"order_{orderId}";
            var cachedOrder = await _fusionCache.GetOrSetAsync(
                cacheKey, async () =>
                {
                    return await _orderRepository.GetOrderById(orderId);
                },
                options => options.SetDuration(TimeSpan.FromMinutes(5)).SetFailSafe(true)
            );

            if (cachedOrder == null)
            {
                return NotFound();
            }
            return Ok(cachedOrder);
        }
    }
}

Eager Refresh in FusionCache

FusionCache offers an eager refresh feature that ensures your cache stays updated. By specifying a cache duration and a refresh threshold, you can have the cache automatically refresh when it’s 50% of the way through its duration.

options => options.SetDuration(TimeSpan.FromMinutes(1))
options => options.SetEagerRefresh(0.5f)

Adaptive Caching in FusionCache

FusionCache also supports adaptive caching, where cache durations adjust based on factors like data update patterns and system load. The cache duration can change dynamically, as shown in the example below:

if (order is null)
{
    Duration = TimeSpan.FromMinutes(3);
}
else if (order.LastUpdateTime > DateTime.UtcNow.AddDays(-1))
{
    Duration = TimeSpan.FromMinutes(1);
}
else
{
    Duration = TimeSpan.FromMinutes(10);
}

FusionCache enhances Microsoft’s HybridCache API with added features like adaptive caching and eager refresh, providing greater flexibility and resiliency. Microsoft has been using FusionCache for improved caching in their applications.