feat: Implementierung von Caching im EmailTemplateRepository zur Leistungsverbesserung der ReadByNameAsync-Methode.

This commit is contained in:
Developer 02 2024-06-06 17:17:06 +02:00
parent f509cc8b3b
commit 0268756cf9

View File

@ -3,16 +3,33 @@ using DigitalData.UserManager.Infrastructure.Repositories;
using EnvelopeGenerator.Domain.Entities; using EnvelopeGenerator.Domain.Entities;
using EnvelopeGenerator.Infrastructure.Contracts; using EnvelopeGenerator.Infrastructure.Contracts;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using static EnvelopeGenerator.Common.Constants; using static EnvelopeGenerator.Common.Constants;
namespace EnvelopeGenerator.Infrastructure.Repositories namespace EnvelopeGenerator.Infrastructure.Repositories
{ {
public class EmailTemplateRepository : CRUDRepository<EmailTemplate, int, EGDbContext>, IEmailTemplateRepository public class EmailTemplateRepository : CRUDRepository<EmailTemplate, int, EGDbContext>, IEmailTemplateRepository
{ {
public EmailTemplateRepository(EGDbContext dbContext) : base(dbContext) private readonly IMemoryCache _cache;
public EmailTemplateRepository(EGDbContext dbContext, IMemoryCache cache) : base(dbContext)
{ {
_cache = cache;
} }
public async Task<EmailTemplate?> ReadByNameAsync(EmailTemplateType type) => await _dbSet.Where(t => t.Name == type.ToString()).FirstOrDefaultAsync(); private readonly Guid key_guid = Guid.NewGuid();
/// <summary>
/// Retrieves an email template based on its name.
/// Utilizes in-memory caching to improve performance for the limited number of email templates available.
/// If the template is not found in the cache, it queries the database and stores the result in the cache.
/// </summary>
/// <param name="type">The type of the email template, which corresponds to its name.</param>
/// <returns>
/// A task that represents the asynchronous operation. The task result contains the email template
/// if found, otherwise null.
/// </returns>
public async Task<EmailTemplate?> ReadByNameAsync(EmailTemplateType type) => await _cache.GetOrCreateAsync($"{type}{key_guid}", async _
=> await _dbSet.Where(t => t.Name == type.ToString()).FirstOrDefaultAsync());
} }
} }