Using Redis in .NET Core


Tags: dotnet
csharp
redis
caching
Redis is one of the most popular in-memory data stores, often used for caching, session management, and real-time data processing. Its speed and simplicity make it an excellent choice for .NET developers who need high-performance solutions.
In this tutorial, we’ll explore how to integrate Redis into a .NET Core application step by step.
Why Redis?
Blazing fast – stores data in memory, not on disk.
Scalable – handles millions of requests per second.
Versatile – supports caching, pub/sub, leaderboards, queues, and more.
Cross-platform – works with Linux, Windows, Docker, and cloud providers.
Prerequisites
.NET 6+ (works with .NET Core 3.1 and later).
A running Redis instance (locally, via Docker, or cloud services like Azure Redis Cache).
👉 To run Redis locally with Docker:
docker run --name redis-demo -d -p 6379:6379 redis
Step 1: Install Redis Package
We’ll use the StackExchange.Redis library (officially maintained by the Stack Overflow team).
dotnet add package StackExchange.Redis
Step 2: Configure Redis in .NET Core
In your Program.cs
(or Startup.cs
for older versions):
using StackExchange.Redis;
var builder = WebApplication.CreateBuilder(args);
// Register Redis connection as a singleton
builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
{
var configuration = builder.Configuration.GetConnectionString("Redis");
return ConnectionMultiplexer.Connect(configuration);
});
var app = builder.Build();
app.MapGet("/", () => "Redis Demo Running!");
app.Run();
Add the Redis connection string in appsettings.json
:
{
"ConnectionStrings": {
"Redis": "localhost:6379"
}
}
Step 3: Create a Redis Service
Let’s build a simple wrapper around Redis to make it easier to use.
using StackExchange.Redis;
using System.Text.Json;
public class RedisCacheService
{
private readonly IDatabase _db;
public RedisCacheService(IConnectionMultiplexer redis)
{
_db = redis.GetDatabase();
}
public async Task SetAsync<T>(string key, T value, TimeSpan? expiry = null)
{
var json = JsonSerializer.Serialize(value);
await _db.StringSetAsync(key, json, expiry);
}
public async Task<T?> GetAsync<T>(string key)
{
var value = await _db.StringGetAsync(key);
if (value.IsNullOrEmpty) return default;
return JsonSerializer.Deserialize<T>(value!);
}
public async Task RemoveAsync(string key)
{
await _db.KeyDeleteAsync(key);
}
}
Step 4: Register and Use the Service
In Program.cs
:
builder.Services.AddScoped<RedisCacheService>();
In a controller:
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly RedisCacheService _cache;
public ProductsController(RedisCacheService cache)
{
_cache = cache;
}
[HttpGet("{id}")]
public async Task<IActionResult> GetProduct(int id)
{
string key = $"product:{id}";
// Try get from cache
var product = await _cache.GetAsync<Product>(key);
if (product != null)
return Ok(product);
// Simulate DB fetch
product = new Product { Id = id, Name = $"Product {id}" };
// Cache it for 1 minute
await _cache.SetAsync(key, product, TimeSpan.FromMinutes(1));
return Ok(product);
}
}
public record Product(int Id, string Name);
Step 5: Verify It Works
Start Redis (
docker ps
should show it running).Run your API.
Fetch
GET /api/products/1
.First request → fetches from DB and caches it.
Next request → retrieves from Redis instantly! 🎉
Common Use Cases
Caching expensive queries (e.g., product details, reports).
Session storage for web applications.
Pub/Sub messaging between services.
Rate limiting (e.g., prevent API abuse).
Best Practices
Use short expiration times to keep cache fresh.
Cache only frequently accessed data.
Handle Redis failures gracefully (fallback to DB).
Monitor Redis performance with tools like RedisInsight.
Conclusion
Redis + .NET Core is a powerful combination for building scalable and high-performance applications. With just a few lines of code, you can implement caching, session management, and more.
If you’re building APIs or microservices in .NET, Redis should definitely be part of your toolbox. 🚀
👉 you can get source code of article from github
What do you think? Have you used Redis in your .NET projects? Share your experiences in the comments!
I’m Morteza Jangjoo and “Explaining things I wish someone had explained to me”
Subscribe to my newsletter
Read articles from Morteza Jangjoo directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
