diff --git a/EnvelopeGenerator.ServiceHost/Jobs/LicenseManagerFactory.cs b/EnvelopeGenerator.ServiceHost/Jobs/LicenseManagerFactory.cs new file mode 100644 index 00000000..e8fae17d --- /dev/null +++ b/EnvelopeGenerator.ServiceHost/Jobs/LicenseManagerFactory.cs @@ -0,0 +1,39 @@ +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."); + } +} \ No newline at end of file