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?
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\$