Azure Redis Cache helpers for your dotnet core projects.
- Add
ICacheService.cs
andCacheService.cs
to your project. - Install nuget package
Microsoft.Extensions.Caching.Redis
package. - Configure your configuration file: Add
RedisConnectionString
key and value. - Configure your
Startup.cs
file : Add connection stringservices.AddDistributedRedisCache(options => options.Configuration = Configuration["RedisConnectionString"]);
- Configure your
Startup.cs
file : Addservices.AddSingleton<ICacheService, CacheService>();
Example controller:
private readonly ICacheService CacheService;
public HomeController(ICacheService cacheService) => CacheService = cacheService;
public async Task<IActionResult> OrganizeCache()
{
// Cache name
const string cacheName = "TestKey";
// Get cache value
Test test = await CacheService.GetCacheAsync<Test>(cacheName);
// Cache value is null
if (test == null)
{
// Create new value
Test testValue = new()
{
Id = 1,
Name = "Cenk"
};
// Set new value
test = await CacheService.SetCacheAsync(cacheName, testValue, 10);
}
ViewBag.Result = test;
return View();
}
Example model:
public record Test
{
public int Id { get; init; }
public string Name { get; init; }
}
Removing cache key
Simply call
await Cache.RemoveCacheAsync("cacheName");