我需要邮寄很多不同的表格。例如
FeedBackForm
ContactsForm
。唯一的区别是我创建了不同的 mail.Subject
和 mail.Body
。
我需要自动执行此操作。
public class EmailService : IEmailService, ITransientService
{
private IConfiguration _configuration;
public EmailService(IConfiguration configuration)
{
_configuration = configuration;
}
public async Task SendFormToAdminEmailAsync (FeedBackForm form)
{
var fromAddress = _configuration["EmailCredentials:Email"];
var fromPassword = _configuration["EmailCredentials:Password"];
var toAddress = new MailAddress("[email protected]");
var mail = new MailMessage(new MailAddress(fromAddress), toAddress);
mail.Subject = $"Need consultation {form.Name}";
mail.Body = $@"Name: {form.Name}
Email: {form.Email}
Phone: {form.PhoneNumber}
Link: {form.BotLink}";
using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
{
smtp.Credentials = new NetworkCredential("[email protected]", fromPassword);
smtp.EnableSsl = true;
await smtp.SendMailAsync(mail);
}
}
}```
I tried this, in this method I accepted a generic type, and with the help of automapper I mapped what I needed, and specified the conditions in MappingConfig, but I don’t know if this is correct
我继续的方法是(如果您还没有)为表单创建一个界面(
FeedbackForm
,ContactForm
)
interface IFormData
{
// Don't know if you have some common ground on forms
// This may be an empty interface to mark types that can be worked with
// in later stages of this solution.
}
您可以创建一个如下界面:
interface IMailHydrator
{
void Hydrate(MailMessage message, IFormData form);
}
比你创建类似的实现
class FeedBackFormHydrator : IMailHydrator
{
public void Hydrate(MailMessage message, IFormData form)
{
var cast = form as FeedBackForm;
if (cast == null)
{
throw new InvalidOperationException();
}
message.Subject = $"Need consultation {cast.Name}";
mail.Body = $@"Name: {cast.Name}
Email: {cast.Email}
Phone: {cast.PhoneNumber}
Link: {cast.BotLink}";
}
}
您在 DI 中将这些水化器注册为命名/密钥注册,其中名称/密钥是表单类型的全名。所以类似:
this.AddSingleton<IMailHydrator, FeedBackFormHydrator>().Named(typeof(FeedBackForm).FullName);
您将方法更改为:
public async Task SendFormToAdminEmailAsync (IFormData form)
{
var fromAddress = _configuration["EmailCredentials:Email"];
var fromPassword = _configuration["EmailCredentials:Password"];
var toAddress = new MailAddress("[email protected]");
var mail = new MailMessage(new MailAddress(fromAddress), toAddress);
var hydrator = this.container.Resolve<IMailHydrator>(form.GetType().FullName);
hydrator.Hydrate(mail, form);
using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
{
smtp.Credentials = new NetworkCredential("[email protected]", fromPassword);
smtp.EnableSsl = true;
await smtp.SendMailAsync(mail);
}
}
根据您的 DI 容器,可能会有一些调整。