如何为asp.net mvc设置电子邮件或通知服务

时间:2011-01-14 01:10:49

标签: asp.net-mvc design-patterns asp.net-mvc-3

如何创建可以模拟和单元测试的电子邮件发送通知服务类?

我的服务在另一层,即一个类库。我试图不导入smtp客户端,但如果这是不可避免的,那么没问题。这就是我现在所拥有的:

public class EmailNotificationService : INotificationService
{
    private readonly EmailNotification _emailNotification;

    public EmailNotificationService(EmailNotification emailNotification)
    {
        _emailNotification = emailNotification;
    }

    public void Notify()
    {
        using (var mail = new MailMessage())
        {
            //If no replyto was passed in the notification, then make it null.
            mail.ReplyTo = string.IsNullOrEmpty(_emailNotification.ReplyTo) ? null : new MailAddress(_emailNotification.ReplyTo);

            mail.To.Add(_emailNotification.To);
            mail.From = _emailNotification.From;
            mail.Subject = _emailNotification.Subject;
            mail.Body = _emailNotification.Body;
            mail.IsBodyHtml = true;

            //this doesn't seem right.
            SmtpClient client = new SmtpClient();
            client.Send(mail);
        }
    }
}

public class EmailNotification
{
    public EmailNotification()
    {
        To = "";
        ReplyTo = "";
        Subject = "";
        Body = "";
    }
    public string To { get; set; }
    public string ReplyTo { get; set; }
    public string Subject { get; set; }
    public string Body { get; set; }

}

1 个答案:

答案 0 :(得分:1)

如果您不想导入System.Net.Mail库,则必须使用接口。请注意,这对您的单元测试没有太大帮助,但

public interface IEmailSender{
     void Send(EmailNotification emailNotification);
}

然后在您的EmailNotificationService类中,您可以添加以下属性或在构造函数中传入IEmailSender

private IEmailSender emailSender;

public IEmailSender EmailSender
{
     get{
          if(this.emailSender == null){
               //Initialize new EmailSender using either
               // a factory pattern or inject using IOC 
          }
          return this.emailSender
     }
     set{
          this.emailSender = value;
     }
}

您的Notify方法将成为

public void Notify()
{
    EmailSender.Send(_emailNotification);
}
然后,您将创建一个实现IEmailSender接口的具体类

public class MyEmailSender: IEmailSender
{
     public void Send(EmailNotification emailNotification)
     {
        using (var mail = new MailMessage())
        {
            //If no replyto was passed in the notification, then make it null.
            mail.ReplyTo = 
                    string.IsNullOrEmpty(_emailNotification.ReplyTo) ? null : 
                    new MailAddress(_emailNotification.ReplyTo);

            mail.To.Add(emailNotification.To);
            mail.From = emailNotification.From;
            mail.Subject = emailNotification.Subject;
            mail.Body = emailNotification.Body;
            mail.IsBodyHtml = true;

            SmtpClient client = new SmtpClient();
            client.Send(mail);
        }
     }
}