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.
39 lines
1.5 KiB
C#
39 lines
1.5 KiB
C#
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<LicenseManager> CreateAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
var key = await GetLicenseKeyAsync(cancellationToken);
|
|
var licenseManager = new LicenseManager();
|
|
licenseManager.RegisterKEY(key);
|
|
return licenseManager;
|
|
}
|
|
|
|
public async Task<string> 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<IMediator>();
|
|
return await mediator.Send(new ReadThirdPartyModuleLicenseQuery { Name = "GdPicture", Active =true }, cancellationToken);
|
|
}) ?? throw new InvalidOperationException("License key could not be retrieved.");
|
|
}
|
|
} |