簡體   English   中英

如何在不破壞我的服務層的情況下使用MVCMailer?

[英]How to use MVCMailer without breaking my service layer?

我正在研究使用MVcMailer制作更好的電子郵件。

但是我不確定的一件事是如何組織代碼。 我目前有2個項目。 一個用於mvc,一個用於我的repos和服務層。

我的第二個項目不了解MVC,我想保持這種方式。

我在想我的smtp代碼會進入服務層或包裝器,然后當我需要發送電子郵件時,我會從其他服務層調用它。

那么MVC郵件適合哪里? 我是否在控制器中生成主體然后將其傳遞給將其傳遞給我的smtp類的服務層?

我的解決方案是在服務層中構建接口,然后我的服務可以使用它來獲取郵件消息,而創建消息的實現繼續駐留在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;
    }
}

最后在服務層,郵件程序接口是服務的依賴:

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類的其他部分。

MVCMailer似乎已經支持發送電子郵件。 如果您正確設置了配置,它應該能夠通過電子郵件發送填充的MailerViews而無需額外的實現。

我不確定您的第二個項目在您的解決方案中的作用,但這里有兩種可能性:

  1. 可能不實用......等待“從后台進程發送電子郵件”的版本

  2. 忘掉你的第二個項目中的Smtp並使用Http只需調用一個View,然后調用MVCMailer

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM