using FreeRedis;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Volo.Abp.Caching;
using Volo.Abp.Modularity;

namespace NPin.Framework.Caching.FreeRedis;

/// <summary>
/// FreeRedis支持分布式缓存(IDistributedCache)，与abp无缝斜街
/// </summary>
[DependsOn(typeof(AbpCachingModule))]
public class NPinFrameworkCachingFreeRedisModule : AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        var configuration = context.Services.GetConfiguration();
        var enabled = configuration["Redis:IsEnabled"];
        if (enabled.IsNullOrEmpty() || bool.Parse(enabled))
        {
            var redisConfiguration = configuration["Redis:Configuration"];
            var redisClient = new RedisClient(redisConfiguration);
            
            context.Services.AddSingleton<IRedisClient>(redisClient);
            context.Services.Replace(ServiceDescriptor.Singleton<IDistributedCache>(new DistributedCache(redisClient)));
        }
    }
}