2009-12-29 90 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