From 1f7eb5d4eaf5639d474a0f44ab7e3deb60f53e7e Mon Sep 17 00:00:00 2001 From: TekH Date: Tue, 14 Apr 2026 21:03:54 +0200 Subject: [PATCH] Add LicenseManagerFactory for GdPicture license caching Introduced LicenseManagerFactory to create and cache GdPicture14 LicenseManager instances. The factory retrieves the license key via MediatR, caches it using IMemoryCache with NeverRemove priority, and registers it with LicenseManager. Dependencies are injected, and the license key is preloaded on instantiation. --- .../Jobs/LicenseManagerFactory.cs | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 EnvelopeGenerator.ServiceHost/Jobs/LicenseManagerFactory.cs 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