using adas_core.Application.Services.Caching;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Models.AppSettings;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace adas_core.Infrastructure.Utils
{
///
/// Provides extension methods for configuring or building cache host instances.
///
public static class CacheHostBuilderExtension
{
public static IHostBuilder UseCache(this IHostBuilder hostBuilder)
{
return hostBuilder.ConfigureServices((context, services) =>
{
services.Configure(context.Configuration.GetSection("CacheSettings"));
services.AddSingleton(sp => sp.GetRequiredService>().Value);
services.AddSingleton();
services.AddSingleton();
// RedisLockProvider obtiene IDatabase de forma lazy a través de una clausura,
// ya que la conexión se establece de forma asíncrona dentro de RedisService.
services.AddSingleton(sp => {
RedisService? svcRef = null;
var lockProvider = new RedisLockProvider(() => svcRef?.Database);
var lockMgr = new LockManagerService(
sp.GetRequiredService>(),
lockProvider);
svcRef = new RedisService(
sp.GetRequiredService>(),
sp.GetRequiredService>(),
lockMgr);
return svcRef;
});
// Inyectamos LockManager con InMemoryLockProvider
services.AddSingleton(sp => {
var lockMgr = new LockManagerService(
sp.GetRequiredService>(),
sp.GetRequiredService());
return new CacheService(lockMgr);
});
services.AddSingleton();
});
}
}
}