using EnvelopeGenerator.Application.ThirdPartyModules.Queries; using GdPicture14; using MediatR; using Microsoft.Extensions.Caching.Memory; namespace EnvelopeGenerator.ServiceHost.Jobs; public class LicenseManagerFactory { private static readonly string _cacheKey = Guid.NewGuid().ToString(); private readonly IServiceScopeFactory scopeFactory; private readonly IMemoryCache cache; public LicenseManagerFactory(IServiceScopeFactory scopeFactory, IMemoryCache cache) { this.scopeFactory = scopeFactory; this.cache = cache; _ = CreateAsync(); // Preload the license key into the cache } public async Task CreateAsync(CancellationToken cancellationToken = default) { var key = await GetLicenseKeyAsync(cancellationToken); var licenseManager = new LicenseManager(); licenseManager.RegisterKEY(key); return licenseManager; } public async Task GetLicenseKeyAsync(CancellationToken cancellationToken = default) { return await cache.GetOrCreateAsync(_cacheKey, async entry => { entry.Priority = CacheItemPriority.NeverRemove; using var scope = scopeFactory.CreateScope(); var mediator = scope.ServiceProvider.GetRequiredService(); return await mediator.Send(new ReadThirdPartyModuleLicenseQuery { Name = "GdPicture", Active =true }, cancellationToken); }) ?? throw new InvalidOperationException("License key could not be retrieved."); } }