From 41e0d4691bc35285bb53d0feeb36870acba5859e Mon Sep 17 00:00:00 2001 From: TekH Date: Fri, 6 Mar 2026 11:54:50 +0100 Subject: [PATCH] Add in-memory caching to ReadDefaultConfigQueryHandler Injected IMemoryCache into ReadDefaultConfigQueryHandler and updated the Handle method to cache the default configuration for 30 minutes. This reduces database queries and improves performance for frequently accessed configuration data. --- .../Queries/ReadDefaultConfigQuery.cs | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/EnvelopeGenerator.Application/Configuration/Queries/ReadDefaultConfigQuery.cs b/EnvelopeGenerator.Application/Configuration/Queries/ReadDefaultConfigQuery.cs index 0edf6f56..82f6314f 100644 --- a/EnvelopeGenerator.Application/Configuration/Queries/ReadDefaultConfigQuery.cs +++ b/EnvelopeGenerator.Application/Configuration/Queries/ReadDefaultConfigQuery.cs @@ -1,10 +1,13 @@ using AutoMapper; using DigitalData.Core.Abstraction.Application.Repository; using DigitalData.Core.Exceptions; +using EnvelopeGenerator.Application.Common; using EnvelopeGenerator.Application.Common.Dto; using EnvelopeGenerator.Domain.Entities; using MediatR; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Caching.Distributed; +using Microsoft.Extensions.Caching.Memory; namespace EnvelopeGenerator.Application.Configuration.Queries; @@ -28,15 +31,19 @@ public class ReadDefaultConfigQueryHandler : IRequestHandler /// /// /// /// - public ReadDefaultConfigQueryHandler(IRepository repo, IMapper mapper) + /// + public ReadDefaultConfigQueryHandler(IRepository repo, IMapper mapper, IMemoryCache cache) { _repo = repo; _mapper = mapper; + _cache = cache; } /// @@ -48,10 +55,15 @@ public class ReadDefaultConfigQueryHandler : IRequestHandler public async Task Handle(ReadDefaultConfigQuery request, CancellationToken cancel) { - var config = request.EnforceSingleResult - ? await _repo.Query.SingleOrDefaultAsync(cancel) - : await _repo.Query.FirstOrDefaultAsync(cancel) + var config = await _cache.GetOrCreateAsync(CacheKey.DefaultConfig, entry => + { + entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30); + return request.EnforceSingleResult + ? _repo.Query.SingleOrDefaultAsync(cancel) + : _repo.Query.FirstOrDefaultAsync(cancel) ?? throw new NotFoundException("Default configuration could not be found. Ensure at least one configuration record exists in the database."); + }); + return _mapper.Map(config); } } \ No newline at end of file