【问题标题】:How to use MVCMailer without breaking my service layer?如何在不破坏我的服务层的情况下使用 MVCMailer?
【发布时间】:2013-12-10 02:41:08
【问题描述】:

我正在考虑使用MVcMailer 制作更好的电子邮件。

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

我的第二个项目不了解 MVC,我想保持这种方式。

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

那么 MVC 邮件程序适用于何处?我是否在控制器中生成主体,然后将其传递给将其传递给我的 smtp 类的服务层?

【问题讨论】:

  • 我想知道您能否提供一些关于您最终如何实现 MVCMailer 的信息?

标签: c# asp.net-mvc asp.net-mvc-3 mvcmailer


【解决方案1】:

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

接口在服务层:

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

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

然后实现在 web (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;
    }
}

最后在服务层,mailer接口是服务的一个依赖:

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();
    }
}

当它在依赖注入中连接时,Web.UserMailer 对象用于 Services.IUserMail 参数来构造 UserCreationService 对象。

我试图让示例保持简单以便易于理解,但是一旦您在服务层中引用了 IMailMessage,您就可以将它发送到您的 SMTP 代码,而不仅仅是调用 Send()我愿意。出于您的目的,您可能需要更多地充实 IMailMessage 接口,以便访问 MvcMailMessage 类的其他部分。

【讨论】:

    【解决方案2】:

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

    我不确定您的第二个项目在您的解决方案中的作用,但这里有两种可能性:

    1. 可能不实用...等等 对于带有“电子邮件发送”的版本 来自后台进程”

    2. 从您的第二个项目中忘记 Smtp 并使用 Http 只需调用一个视图 这反过来会调用 MVCMailer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-04
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 2011-02-05
      • 1970-01-01
      • 2010-12-21
      相关资源
      最近更新 更多