2011-03-27 139 views
9

我正在研究使用MVcMailer来制作更好的电子邮件。如何在不破坏服务层的情况下使用MVCMailer?

但是我不确定的一件事是如何组织代码。我目前有2个项目。一个用于mvc,另一个用于我的回购和服务层。

我的第二个项目没有MVC的知识,我想保持这种方式。

我在想,我的smtp代码会进入服务层或包装,然后当我需要发送电子邮件时,我会从其他服务层调用它。

那么MVC邮件适合在哪里?我是否在控制器中生成身体,然后将它传递给一个将它传递给我的smtp类的服务层?

+0

我想知道您是否可以提供一些关于如何实现MVCMailer的信息? – Neil 2013-05-15 09:13:37

回答

0

MVCMailer似乎已经支持发送电子邮件。如果您正确设置配置,它应该能够通过电子邮件发送填充的MailerView而无需额外的实施。

我不知道你的第二个项目在你的解决方案中的作用,但这里有两种可能:

  1. 可能不实用......等待 的版本“电子邮件从后台发送 流程”

  2. 从你的第二个项目 忘掉SMTP和使用HTTP只是调用视图 这反过来会调用MVCMailer

1

我的解决方案是在服务层中构建接口,然后我的服务可以用来获取邮件消息,而创建消息的实现继续驻留在Web层中。

的接口是在服务层:

public interface IMailMessage 
{ 
    void Send(); 
    void SendAsync(); 
} 

public interface IUserMailer 
{ 
    IMailMessage Welcome(WelcomeMailModel model); 
} 

的实现是随后在所述幅材(MVC)项目:

public class MailMessage : MvcMailMessage, IMailMessage 
{ 

} 

public class UserMailer : MailerBase, IUserMailer 
{ 
    public UserMailer() 
    { 
     MasterName = "_Layout"; 
    } 

    public IMailMessage Welcome(WelcomeMailModel model) 
    { 
     var mailMessage = new MailMessage(); 
     mailMessage.SetRecipients(model.To); 
     mailMessage.Subject = "Welcome"; 

     ViewData = new System.Web.Mvc.ViewDataDictionary(model); 
     PopulateBody(mailMessage, "Welcome"); 

     return mailMessage; 
    } 
} 

最后,在服务层,所述邮件收发器接口是一个依赖的服务:

public class UserCreationService : IUserCreationService 
{ 
    private readonly IUserRepository _repository; 
    private readonly IUserMailer _userMailer; 

    public UserCreationService(IUserRepository repository, IUserMailer userMailer) 
    { 
     _repository = repository; 
     _userMailer = userMailer; 
    } 

    public void CreateNewUser(string name, string email, string password) 
    { 
     // Create the user's account 
     _repository.Add(new User { Name = name, Email = email, Password = password }); 
     _repository.SaveChanges(); 

     // Now send a welcome email to the user 
     _userMailer.Welcome(new WelcomeMailModel { Name = name, To = email }).Send(); 
    } 
} 

当它在依赖注入,一个网络连线。 UserMailer对象用于Services.IUserMail参数来构造UserCreationService对象。

我试着保持这个例子简单易懂,但是一旦您在服务层中引用IMailMessage,就可以将它发送到您的SMTP代码而不是仅仅调用Send()像我这样做。出于您的目的,您可能需要充实IMailMessage接口以访问MvcMailMessage类的其他部分。