6
\$\begingroup\$

I have multiple tables and multiple email templates which will need tags replacing. The data for the tags depends on the recipient id as the data will need to be fetched from different tables.

I have a dictionary and register a different email sender depending on the enum like this:

public class EmailService { private readonly Dictionary<SluRecipients, IEmailSender> _emailSenders; private readonly ReghoundContext _context; public EmailService(ReghoundContext context, IServiceProvider serviceProvider) { _context = context; _emailSenders = new Dictionary<SluRecipients, IEmailSender> { { SluRecipients.Alert, serviceProvider.GetService<IAlertEmailSender>() ?? throw new InvalidOperationException("Service cannot be registered") }, { SluRecipients.Company, serviceProvider.GetService<ICompanyEmailSender>() ?? throw new InvalidOperationException("Service cannot be registered") }, { SluRecipients.Invitation, serviceProvider.GetService<IInvitationEmailSender>() ?? throw new InvalidOperationException("Service cannot be registered") } }; } public async Task SendEmailAsync(int emailTemplateId, SendEmailRequest request) { var emailTemplate = await _context.TblEmailTemplates.FirstOrDefaultAsync(t => t.EmtpId == emailTemplateId); if (!_emailSenders.TryGetValue((SluRecipients)emailTemplate.ErecId, out var emailSender) || emailSender == null) { throw new InvalidOperationException($"No email sender found for key: {emailTemplate.ErecId}"); } await emailSender.SendEmailAsync(emailTemplate, request); } } 

Now for email senders I have a base class which sends email alongside override methods to generate different content. e.g

public abstract class EmailSenderBase(DbContext context, IEmailRepository emailRepository, IEmailContentProcessor contentProcessor) : IEmailSender { protected readonly DbContext _context = context; protected readonly IEmailRepository _emailRepository = emailRepository; protected readonly IEmailContentProcessor _contentProcessor = contentProcessor; public async Task SendEmailAsync(TblEmailTemplate template, SendEmailRequest request) { var data = await GetDataAsync(request) ?? throw new InvalidOperationException("Could not find data"); var subject = await ProcessContentAsync(template.EmtpSubject, data, true); var body = await ProcessContentAsync(template.EmtpBody, data, false); var recipientEmails = GetRecipientEmails(template.ErecId, data); await _emailRepository.SendEmailAsync(recipientEmails, subject, body, body); } protected abstract Task<object> GetDataAsync(SendEmailRequest request); protected abstract Task<string> ProcessContentAsync(string content, object data, bool isSubject); protected abstract string[] GetRecipientEmails(int recipientType, object data); } 

Then in a concrete email sender the methods can be overridden like this:

public class AlertEmailSender(DbContext context, IEmailRepository emailRepository, IAlertEmailContentProcessor contentProcessor) : EmailSenderBase(context, emailRepository, contentProcessor), IAlertEmailSender { protected override async Task<object> GetDataAsync(SendEmailRequest request) { if (request.AlertId == null) throw new ArgumentNullException(nameof(request)); return await _context.TblAlerts.FindAsync(request.AlertId) ?? throw new InvalidOperationException("Alert not found"); } protected override string[] GetRecipientEmails(int recipientType, object data) { var alert = (TblAlert)data; return alert.AlertEmails.Split(","); } protected override async Task<string> ProcessContentAsync(string content, object data, bool isSubject) { return await contentProcessor.ProcessContentAsync(content, data, isSubject); } } 

Then in each email sender I will replace content like this (this is done inside an IContentProcessor and will have a different one for each email sender.)

 public partial class AlertEmailContentProcessor(ReghoundContext context) : ContentProcessorBase, IAlertEmailContentProcessor { public async Task<string> ProcessContentAsync(string content, object data, bool isSubject) { var alert = (TblAlert)data; var tags = await context.SluEmailTags.Where(t => isSubject ? t.EmtgIsSubject : t.EmtgIsBody).ToListAsync(); var regex = EmailTagRegex(); var matches = regex.Matches(content); foreach (Match match in matches.Cast<Match>()) { var tagName = match.Groups[1].Value; var tag = tags.FirstOrDefault(t => t.EmtgName == tagName); if (tag == null) continue; if (tagName == SluEmailTags.AlertRecipient.EmtgName) { content = content.Replace(match.Value, alert.AlertRecipient); } } return content; } } 

This is the basic functionality I am going with but this solution seems flawed in many ways. Has anyone done something similar and have a better approach than this?

Concerns

  • Is this approach overcomplicated?
  • Is there a simpler solution / design pattern?
  • Is the service selector pattern in email service class bad practice?
\$\endgroup\$
9
  • \$\begingroup\$My next code in this site will be about something you are doing. think about connections..., connections are a kind of interligated tables and other connections... but i'm trying to do only with jumps, to improve performance...\$\endgroup\$
    – user284928
    CommentedAug 5, 2024 at 19:47
  • 3
    \$\begingroup\$could you please share a template sample , to know how things works currently on your side.? also, does your templates only used for emails or do you use templates on other parts of the system as well?\$\endgroup\$
    – iSR5
    CommentedAug 6, 2024 at 14:22
  • \$\begingroup\$@iSR5 I think this can be used in any type of structure. In my comment. I said connection. In reality, I have tried to do only with the thing of dualism. My connection only has two key-value. So, the navegation, I was trying to do only with jumps. I don't know how is the programming of the real dictionary. Some particularity that maybe dictionary does and my don't. Run a function... But answer your question, this can be done and any type of structure...\$\endgroup\$
    – user284928
    CommentedAug 8, 2024 at 7:09
  • 2
    \$\begingroup\$@vanzuita I understand if you have a similar question as OPs. However, you will need to post your own question about it, and the community will gladly cooperate with their expertise. Every question is unique, this question might have a narrowed answer, while yours might have a more wider and general scope, which might not be that beneficial to the OP.\$\endgroup\$
    – iSR5
    CommentedAug 8, 2024 at 8:35
  • 1
    \$\begingroup\$Why did you allow null value for IEmailSender inside _emailSenders? If it is null then you turn it into an IOE. Without context it does not make too much sense for me.\$\endgroup\$CommentedAug 8, 2024 at 11:41

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.