TaskHub.Shared

Redis Usage

TaskHub.Shared uses Redis primarily for distributed caching and state management, leveraging the standard IDistributedCache interface.

Configuration

Add the Redis section to your appsettings.json.

"Redis": {
  "Endpoint": "localhost:6379",
  "InstanceName": "TaskHub-Cache"
}

Registration

Use the AddAppRedis extension method to register Redis in your service collection.

using TaskHub.Shared.Persistence.Redis;

builder.Services.AddAppRedis(builder.Configuration.GetSection("Redis").Bind);

This registers an IDistributedCache implementation backed by Redis.

Usage

Inject IDistributedCache into your services.

using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;

public class MyCacheService(IDistributedCache cache)
{
    public async Task<T?> GetOrSetAsync<T>(string key, Func<Task<T>> factory, CancellationToken ct)
    {
        var cachedData = await cache.GetStringAsync(key, ct);
        if (cachedData != null)
        {
            return JsonSerializer.Deserialize<T>(cachedData);
        }

        var data = await factory();
        await cache.SetStringAsync(key, JsonSerializer.Serialize(data), new DistributedCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
        }, ct);

        return data;
    }
}

Why use InstanceName?

The InstanceName property in configuration acts as a prefix for all keys stored in Redis. This is crucial in microservice environments where multiple services might share a single Redis cluster, ensuring that keys from different services do not collide.