2009-12-29 91 views
1

知道这已被问过,但是我的问题稍有不同。将事件添加到接口/实现

我有一个接口:

IEmailDispatcher

它看起来像这样:

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

这样一点背景:

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

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

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

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

我怎么会去这样做呢?

或者,有没有更好的办法?

目前,我使用的是“BasicEmailDispatch呃“基本上使用System.Net命名空间,创建一个MailMessage并发送它。

在未来,我将创建另一个类,即处理邮件不同......它添加到SQL数据库表报告等....等将以不同的方式处理OnEmailSent事件到BasicEmailDispatcher

回答

2
public interface IEmailDispatcher 
{ 
    event EventHandler EmailSent; 
    void SendEmail(string[] to, string fromName, string fromAddress, string subject, string body, bool bodyIsHTML, Dictionary<string, byte[]> Attachments); 
} 

欲了解更多详情,看看here.

这是你要找的答案?

0

添加事件到您的接口:

public interface IEmailDispatcher 
{ 
    void SendEmail(string[] to, string fromName, string fromAddress, string subject, string body, bool bodyIsHTML, Dictionary<string, byte[]> 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; } 
    } 
} 
3

它看起来就像试图将所有东西都放到静态类中让你在这里做一些尴尬的事情(特别是使用静态类实现the template pattern)。如果调用者(应用程序)只需要知道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() {} 
} 

更复杂的实现将分别从BasicEmailDispatcher继承(并因此实现IEmailDispatcher)和覆盖一个或两个虚拟方法来提供成功或失败的行为:

public class EmailDispatcherWithLogging: EmailDispatcherBase { 
    protected override OnEmailFailed() { 
     // Write a failure log entry to the database 
    } 
} 
+0

我不知道如何实现这 - 哪里我的静态类适合的?来电者的“入口点”...? 例如,我有BasicEmailDispatcher,DummyEmailDispatcher ...他们仍然执行IEmailDispatcher吗?或BaseEmailDispatcher ... – Alex 2009-12-29 22:29:39

+0

另外 - 什么原因导致每个EmailSent和EmailFailed事件在每个实现中都会有所不同... – Alex 2009-12-29 23:19:39

+0

对不起 - 我误解了你的需求!在修改我的答案的过程中,我试图澄清一点。至于你的静态类,这真的是一个单独的问题 - 你可以继续使用它,因为你一直在做。 (尽管我建议阅读关于单例和依赖注入的StackOverflow!) – 2009-12-30 01:12:58