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.
69 lines
2.1 KiB
C#
69 lines
2.1 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
public record ReadDefaultConfigQuery : IRequest<ConfigDto>
|
|
{
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
public bool EnforceSingleResult { get; init; }
|
|
}
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
public class ReadDefaultConfigQueryHandler : IRequestHandler<ReadDefaultConfigQuery, ConfigDto>
|
|
{
|
|
private readonly IRepository<Config> _repo;
|
|
|
|
private readonly IMapper _mapper;
|
|
|
|
private readonly IMemoryCache _cache;
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
/// <param name="repo"></param>
|
|
/// <param name="mapper"></param>
|
|
/// <param name="cache"></param>
|
|
public ReadDefaultConfigQueryHandler(IRepository<Config> repo, IMapper mapper, IMemoryCache cache)
|
|
{
|
|
_repo = repo;
|
|
_mapper = mapper;
|
|
_cache = cache;
|
|
}
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
/// <param name="request"></param>
|
|
/// <param name="cancel"></param>
|
|
/// <returns></returns>
|
|
/// <exception cref="InvalidOperationException"></exception>
|
|
public async Task<ConfigDto> Handle(ReadDefaultConfigQuery request, CancellationToken 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<ConfigDto>(config);
|
|
}
|
|
} |