我有一个电子邮件服务,它通过构造函数传递电子邮件模型,并且都使用相同的基类。例如,一个模型可用于身份验证,另一个模型用于密码重置。我的问题是如何允许服务传递具有相同基类的匿名模型。
示例代码:
public class EmailService<T> : IEmailService
{
private readonly T _emailModel;
private readonly EmailType _emailType;
private readonly IEmailRepository _emailRepository;
private MailBuilder _mailBuilder;
private EmailTemplates _message;
public EmailService(T emailModel, EmailType emailType, IEmailRepository emailRepository)
{
_emailModel = emailModel;
_emailType = emailType;
_emailRepository = emailRepository;
getMessage();
constructEmail();
}
private void getMessage()
{
_message = _emailRepository.GetTemplateByUser((int)_emailType, _emailModel.UserTypeId);
}
private void constructEmail()
{
_mailBuilder = new MailBuilder(_message, _emailType, ObjectConverters.ConvertProperiesToDictionary(_emailModel));
}
public void Send()
{
EmailSettings emailSettings = SiteSettingsService.SiteConfiguration.EmailSettings;
MailSettings settings = new MailSettings
{
MailFrom = emailSettings.MailFrom,
MailSmtpHost = emailSettings.SmtpHost,
MailSmtpPort = emailSettings.SmtpPort,
EnableSsi = emailSettings.EnableSsi,
MailSmtpUsername = emailSettings.SmtpUsername,
MailSmtpPassword = emailSettings.SmtpPassword
};
new EmailSender(settings).SendEmail(_emailModel.EmailAddress, _message.Title, _mailBuilder.HtmlTemplate);
}
}
答案 0 :(得分:2)
您可以让派生类都实现一个新的IModel
接口,然后您的EmailService
类通过ctor接受。
public class AuthenticationModel : BaseModel, IModel
{
public void PerformMainFunction()
{
// authenticate
}
}
public class PasswordResetModel : BaseModel, IModel
{
public void PerformMainFunction()
{
// reset password
}
}
public class BaseModel
{
public int UserTypeId { get; set; }
}
public interface IModel
{
void PerformMainFunction();
int UserTypeId { get; set; }
}
public class EmailService : IEmailService
{
private readonly IModel _emailModel;
...
public EmailService(IModel emailModel, EmailType emailType, IEmailRepository emailRepository)
{
_emailModel = emailModel;
...
您可以使用类似Unity的内容来注入依赖项,或者,现在,只需执行:
IModel model = new AuthenticationModel();
var eServ = new EmailService(model, ....
答案 1 :(得分:0)
我想到了一个更好的方法。我们总是将对象转换为服务中的字典。也许我们从调用电子邮件服务的服务转换它,所以我们总是传递字典而不是接口,这样我们就不需要知道结构了。字典将始终是字符串和字符串的键值。