feat: updated caching support

- feat: Added memory caching support
- feat: refactored dependency injection methods
This commit is contained in:
2025-05-19 10:29:52 -06:00
parent f694b9a41a
commit ffed92e85c
6 changed files with 116 additions and 17 deletions

View File

@@ -1,4 +1,6 @@
using Microsoft.Extensions.Configuration;
using Core.Blueprint.Caching;
using Core.Blueprint.Caching.Contracts;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
@@ -17,23 +19,32 @@ namespace Core.Blueprint.Redis.Configuration
/// <returns>The updated service collection.</returns>
public static IServiceCollection AddRedis(this IServiceCollection services, IConfiguration configuration)
{
// Retrieve the Redis connection string from the configuration.
// Get Redis configuration section
var redisConnectionString = configuration.GetSection("ConnectionStrings:Redis").Value;
if (string.IsNullOrEmpty(redisConnectionString))
// TODO for the following variable we'll need to add in the appsettings.json the following config: "UseRedisCache": true,
bool useRedis = configuration.GetValue<bool>("UseRedisCache");
//TODO decide wheter to use appsettings or the following ENV variable
useRedis = Environment.GetEnvironmentVariable("CORE_BLUEPRINT_PACKAGES_USE_REDIS")?.ToLower() == "true";
if (useRedis)
{
throw new InvalidOperationException("Redis connection is not configured.");
var redisConnectionString = configuration.GetSection("ConnectionStrings:Redis").Value;
if (string.IsNullOrEmpty(redisConnectionString))
{
throw new InvalidOperationException("Redis connection is not configured.");
}
services.AddSingleton<ICacheProvider>(provider =>
new RedisCacheProvider(redisConnectionString, provider.GetRequiredService<ILogger<RedisCacheProvider>>()));
}
else
{
services.AddMemoryCache();
services.AddSingleton<ICacheProvider, MemoryCacheProvider>();
}
// Register RedisCacheProvider
services.AddSingleton<IRedisCacheProvider>(provider =>
new RedisCacheProvider(redisConnectionString, provider.GetRequiredService<ILogger<RedisCacheProvider>>()));
// Get CacheSettings and register with the ICacheSettings interface
var cacheSettings = configuration.GetSection("CacheSettings").Get<CacheSettings>();
if (cacheSettings == null)
{
throw new InvalidOperationException("Redis CacheSettings section is not configured.");
throw new InvalidOperationException("CacheSettings section is not configured.");
}
services.AddSingleton<ICacheSettings>(cacheSettings);