I'd like to implement a microservice to send emails using a fallback client, so in case of failure in the first client (SendGrid) I'll call the second client (MailJet), the code below shows the idea.
The questions is: Is there a way to improve the Main function using some .net core feature instead of initialize new objects? The point is that I'd like to follow SOLID principles avoiding dependencies and tight couplings, so if I need a new EmailClient tomorrow it should be easy to implement without break SOLID principles.
P.S. Any improvement is welcome.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<IEmailClient> clients = new List<IEmailClient>();
clients.Add(new SendGrid());
clients.Add(new MailJet());
var emailService = new EmailService(clients);
emailService.sendEmail();
}
}
public class EmailService
{
protected List<IEmailClient> clients;
public EmailService(List<IEmailClient> clients)
{
this.clients = clients;
}
public void sendEmail()
{
foreach (IEmailClient client in this.clients)
{
if (client.send()) {
break;
}
}
}
}
public interface IEmailClient
{
bool send();
}
public class SendGrid: IEmailClient
{
public bool send()
{
var error = true;
Console.WriteLine("SendGrid sending email");
if (error) {
Console.WriteLine("Error");
return false;
}
Console.WriteLine("Sendgrid email sent");
return true;
}
}
public class MailJet: IEmailClient
{
public bool send()
{
var error = false;
Console.WriteLine("Mailjet sending email");
if (error) {
Console.WriteLine("Error");
return false;
}
Console.WriteLine("Mailjet email sent");
return true;
}
}