将事件添加到接口/实现

知道以前曾经问过,但我的问题略有不同。

我有一个界面:

IEmailDispatcher

它看起来像这样:

public interface IEmailDispatcher { void SendEmail(string[] to, string fromName, string fromAddress, string subject, string body, bool bodyIsHTML, Dictionary Attachments); } 

作为一点背景:

我有一个静态EmailDispatcher类,它具有以下方法:SendEmail(string [] to,string fromName,string fromAddress,string subject,string body,bool bodyIsHTML,Dictionary Attachments);

然后,通过IoC,加载相关的IEmailDispatcher实现,并调用该方法。

我的应用程序可以简单地调用EmailDispatcher.SendEmail(………

我想向它添加事件,例如OnEmailSent,OnEmailFail等……这样每个实现都可以处理发送电子邮件的成功和失败,并相应地记录它们。

我该怎么做呢?

或者,还有更好的方法?

目前,我正在使用“BasicEmailDispatcher”,它基本上使用System.Net命名空间,创建MailMessage并发送它。

在将来,我将创建另一个类,以不同的方式处理邮件…将其添加到sql db表以进行报告等….因此将以不同的方式处理OnEmailSent事件到BasicEmailDispatcher

看起来试图将所有东西都放到静态类中会让你在这里做一些尴尬的事情(具体来说,使用静态类来实现模板模式 )。 如果调用者(应用程序)只需要知道SendEmail方法,那么这是接口中应该唯一的东西。

如果确实如此,您可以让您的基本调度程序类实现模板模式:

 public class EmailDispatcherBase: IEmailDispatcher { // cheating on the arguments here to save space public void SendEmail(object[] args) { try { // basic implementation here this.OnEmailSent(); } catch { this.OnEmailFailed(); throw; } } protected virtual void OnEmailSent() {} protected virtual void OnEmailFailed() {} } 

更复杂的实现将从BasicEmailDispatcherinheritance(因此实现IEmailDispatcher )并覆盖一个或两个虚方法以提供成功或失败行为:

 public class EmailDispatcherWithLogging: EmailDispatcherBase { protected override OnEmailFailed() { // Write a failure log entry to the database } } 
 public interface IEmailDispatcher { event EventHandler EmailSent; void SendEmail(string[] to, string fromName, string fromAddress, string subject, string body, bool bodyIsHTML, Dictionary Attachments); } 

有关详细信息,请查看此处。

这是你正在寻找的答案吗?

将事件添加到您的界面:

 public interface IEmailDispatcher { void SendEmail(string[] to, string fromName, string fromAddress, string subject, string body, bool bodyIsHTML, Dictionary Attachments); event EmailSentEventHandler EmailSent; event EmailFailedEventHandler EmailFailed; } 

在静态类中,使用显式事件访问器来订阅实际实现的事件:

 public static class EmailDispatcher { public event EmailSentEventHandler EmailSent { add { _implementation.EmailSent += value; } remove { _implementation.EmailSent -= value; } } public event EmailFailedEventHandler EmailFailed { add { _implementation.EmailFailed += value; } remove { _implementation.EmailFailed -= value; } } }