TaskHub.Shared uses Redis primarily for distributed caching and state management, leveraging the standard IDistributedCache interface.
Add the Redis section to your appsettings.json.
"Redis": {
"Endpoint": "localhost:6379",
"InstanceName": "TaskHub-Cache"
}
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.
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;
}
}
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.