Files
Core.BluePrint.Packages/Core.Blueprint.Redis/Configuration/RegisterBlueprint.cs
Efrain Marin 398ca3d7b6 fix: updated namespaces
- code cleanup, removed unused usings
2025-05-19 10:32:59 -06:00

54 lines
2.4 KiB
C#

using Core.Blueprint.Caching.Adapters;
using Core.Blueprint.Caching.Contracts;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Core.Blueprint.Caching.Configuration
{
/// <summary>
/// Provides extension methods for registering Redis-related services in the DI container.
/// </summary>
public static class RegisterBlueprint
{
/// <summary>
/// Adds Redis caching services to the service collection.
/// </summary>
/// <param name="services">The service collection to register the services into.</param>
/// <param name="configuration">The application configuration object.</param>
/// <returns>The updated service collection.</returns>
public static IServiceCollection AddRedis(this IServiceCollection services, IConfiguration configuration)
{
// 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)
{
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>();
}
var cacheSettings = configuration.GetSection("CacheSettings").Get<CacheSettings>();
if (cacheSettings == null)
{
throw new InvalidOperationException("CacheSettings section is not configured.");
}
services.AddSingleton<ICacheSettings>(cacheSettings);
return services;
}
}
}