52 lines
		
	
	
		
			2.2 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
			
		
		
	
	
			52 lines
		
	
	
		
			2.2 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");
 | |
| 
 | |
|             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;
 | |
|         }
 | |
|     }
 | |
| } | 
