I have been looking into stuff like method chaining, Cascade-Lambda pattern etc.
I have created a class which seems to work fine. However, I just wanted to confirm if this is the best way and the right way to implement this.
For the cascade lambda pattern I was unable to use Action<MailManager> action
as a parameter to the Send()
method. I couldn't figure out how would I use it Any suggestions are welcome.
Here is the code:
public class MailManager
{
MailMessage _mail { get; set; }
SmtpClient _smtp { get; set; }
public MailManager To(string address)
{
_mail.From = new MailAddress(address);
return this;
}
public MailManager From(string address)
{
_mail.To.Add(new MailAddress(address));
return this;
}
public MailManager Subject(string subject)
{
_mail.Subject = subject;
return this;
}
public MailManager Body(string body)
{
_mail.Body = body;
return this;
}
public MailManager IsBodyHtml(bool isBodyHtml = true)
{
_mail.IsBodyHtml = isBodyHtml;
return this;
}
public MailManager AlternateViews(AlternateView alternateView)
{
_mail.AlternateViews.Add(alternateView);
return this;
}
public MailManager Host(string host)
{
_smtp.Host = host; return this;
}
public MailManager Port(int port)
{
_smtp.Port = port; return this;
}
public MailManager Credentials(NetworkCredential credentials)
{
_smtp.Credentials = credentials; return this;
}
public MailManager EnableSsl(bool enableSsl = true)
{
_smtp.EnableSsl = enableSsl; return this;
}
public static void Send(MailMessage mail, SmtpClient smtp)
{
using (smtp)
{
smtp.Send(mail);
}
}
public void Send()
{
using (_smtp)
{
_smtp.Send(_mail);
}
}
}
Aucun commentaire:
Enregistrer un commentaire