2

現在、db リストをループする電子メールを送信するための 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>");
                    }

必要に応じてメーラーの実装を簡単に交換できるように、このステートメントを一種のサービスに分割する方法を考えています。これを達成するための最良の方法を説明できる良い例はありますか?

4

1 に答える 1

1

最も単純で複雑でない例では、インターフェースを作成するだけです。

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の例があります。

于 2012-07-31T16:16:28.553 に答える