目前,我有一个 Controller 方法,其中包含一个 try/catch 语句,用于发送循环遍历数据库列表的电子邮件:
try
{
// MailSender object declaration
MailSender objMail = new MailSender();
// Set SMTP server address
objMail.Host = "smtp.test.com";
// Sender's address
objMail.From = "test@test.com";
// Subject
objMail.Subject = surveyprogrammodel.Subject;
// HTML format?
objMail.IsHTML = true;
//Send to Mail Queue
objMail.Queue = true;
objMail.QueuePath = Server.MapPath("~\\MailQueue\\");
foreach (var item in EmailList)
{
// Create dynamic link to the take the Survey
var SurveyLink = strUrl + UrlContent + "SurveyResponse/Create?MemberId=" + item.PersonModels.MemberId + "&ProgramId=" + item.ProgramId;
// Recipient's address
objMail.AddAddress(item.PersonModels.Email);
// Body
objMail.Body = surveyprogrammodel.Body + "<br /><br />Please take the survey using the link below:<br /><br /><a href=\"" + SurveyLink + "\">" + SurveyLink + "<a/>";
// Send message
objMail.Send();
objMail.ResetAddresses();
}
}
catch (Exception ex)
{
Response.Write("An error occurred: <font color=red>"+ ex.Message + "</font>");
}
我想知道如何将此语句分解为一种服务,以便在需要时可以轻松交换邮件程序实现。是否有一个很好的例子可以解释实现这一目标的最佳方法?
最佳答案
在最简单、不复杂的示例中,您可以简单地创建一个接口(interface)。
interface IEmailer
{
void Send(List<Email> email);
}
class SimpleMailer : IEmailer
{
void Send(List<Email> email)
{
//do work
}
}
class ComplexMailer : IEmailer
{
void Send(List<Email> email)
{
//do work
}
}
用法
IEmailer mailer = new SimpleMailer();
实现变更
IEmailer mailer = new ComplexMailer();
然后,如果您想要查找样式实现,您可以实现服务定位器模式/使用 DI 框架(StructureMap、Ninject 等)。 MSDN 上有一个示例 here .
关于c# - 向我的应用程序添加服务层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11743760/