Skip to content

cenksari/aspnet-core-rediscache

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Azure Redis Cache helpers

Azure Redis Cache helpers for your dotnet core projects.

How to install

  1. Add ICacheService.cs and CacheService.cs to your project.
  2. Install nuget package Microsoft.Extensions.Caching.Redis package.
  3. Configure your configuration file: Add RedisConnectionString key and value.
  4. Configure your Startup.cs file : Add connection string services.AddDistributedRedisCache(options => options.Configuration = Configuration["RedisConnectionString"]);
  5. Configure your Startup.cs file : Add services.AddSingleton<ICacheService, CacheService>();

How to use

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");