Distributed Caching with Redis in .NET
Significantly improve the performance of your .net apps using distributed caching.
Install Microsoft.Extensions.Caching.StackExchangeRedis
nuget package
Add RedisConfiguration section to your appsettings.json
"RedisConfiguration": {
"Host": "your-awesome.host.com",
"Port": 6379,
"IsSSL": true,
"Password": "YourSecur3Pa$$w0rD"
}
and create a matching options model for binding
internal class RedisConfigurationOptions
{
public string Host { get; set; } = string.Empty;
public int Port { get; set; }
public bool Ssl { get; set; } = true;
public string Password { get; set; } = string.Empty;
}
Configure it in the DI container
// Configure Redis
var redisConfig = configuration
.GetSection("RedisConfiguration")
.Get<RedisConfigurationOptions>()
?? throw new InvalidOperationException("RedisConfiguration is missing or invalid.");
services.AddSingleton<IConnectionMultiplexer>(option => ConnectionMultiplexer.Connect(
new ConfigurationOptions
{
EndPoints = { $"{redisConfig.Host}:{redisConfig.Port}" },
AbortOnConnectFail = false,
Ssl = redisConfig.Ssl,
Password = redisConfig.Password,
}));
services.AddDistributedMemoryCache();