我正在考虑使用 MVcMailer制作更好的电子邮件。
但是我不确定的一件事是如何组织代码。我目前有 2 个项目。一个用于 mvc,一个用于我的存储库和服务层。
我的第二个项目不了解 MVC,我想保持这种状态。
我想我的 smtp 代码会进入服务层或包装器,然后当我需要发送电子邮件时,我会从其他服务层调用它。
那么 MVC 邮件程序适合什么地方呢?我是否在 Controller 中生成正文,然后将其传递到服务层,再将其传递到我的 smtp 类?
最佳答案
我的解决方案是在服务层构建接口(interface),然后我的服务可以使用这些接口(interface)来获取邮件消息,而创建消息的实现继续驻留在 Web 层。
接口(interface)在服务层:
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接口(interface)是服务的依赖:
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();
}
}
在依赖注入(inject)中连接时,Web.UserMailer 对象用于 Services.IUserMail 参数以构造 UserCreationService 对象。
我尽量让示例保持简单,以便于理解,但是一旦您在服务层中引用了 IMailMessage,您就可以将它发送到您的 SMTP 代码,而不仅仅是调用 Send() 作为我愿意。出于您的目的,您可能需要进一步充实 IMailMessage 接口(interface),以便访问 MvcMailMessage 类的其他部分。
关于c# - 如何在不破坏我的服务层的情况下使用 MVCMailer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5453108/