2012-06-26 96 views
2

我使用MVC模式實現了WinForms應用程序,其中Model從View(Form)異步運行(backgroundWorker線程)。視圖訂閱了從Model引發的一對事件。WCF中的事件委託類比

現在我需要將其轉換爲WCF應用程序,其中event-eventHandler概念必須存在。
起初,我想通過回調接口實現這一點,但在我的情況下,來自Model的一種方法引發了多種類型的事件,並且在定義服務合同時受到單個回調接口的限制。

此時我想出了在回調服務中將不同類型的事件指定爲方法並在客戶端實現的想法。例如:

public interface ICallbacks 
{ 
    [OperationContract(IsOneWay = true)] 
    void EventHandler1(); 

    [OperationContract(IsOneWay = true)] 
    void EventHandler2(string callbackValue); 

    [OperationContract(IsOneWay = true)] 
    void EventHandler3(string callbackValue); 
} 

我應該配合這個解決方案還是有一些更好的選擇(發佈 - 訂閱wcf模式)?

回答

0

您可以使用單一的方法有一個基本類型參​​數,可以激活你的電話。然後在你的服務代碼中,根據事件的類型跳轉到特定的處理程序。

public class BaseEvent { } 

public class MyFirstEvent : BaseEvent { } 

public class MySecondEvent : BaseEvent { } 

public class MyThirdEvent : BaseEvent { } 


public interface ICallbacks 
{ 
    [OperationContract(IsOneWay = true)] 
    void EventHandler(BaseEvent myEvent); 
} 

public class MyService : ICallbacks 
{ 
    public void EventHandler(BaseEvent myEvent) 
    { 
     //Now you can check for the concrete type of myEvent and jump to specific method. 
     //e.g.: 
     if (myEvent is MyFirstEvent) 
     { 
     //Call your handler here. 
     } 


     //Another approach can be predefined dictionary map of your event handlers 
     //You want to define this as static map in class scope, 
     //not necessarily within this method. 
     Dictionary<Type, string> map = new Dictionary<Type, string>() 
     { 
     { typeof(MyFirstEvent), "MyFirstEventHandlerMethod" }, 
     { typeof(MySecondEvent), "MySecondEventHandlerMethod" } 
     { typeof(MyThridEvent), "MyThirdEventHandlerMethod" } 
     }; 

     //Get method name from the map and invoke it. 
     var targetMethod = map[myEvent.GetType()]; 
     this.GetType().GetMethod(targetMethod).Invoke(myEvent); 
    } 
} 
0

使用雙工是不是一個好主意,除非你的應用程序在相同的運行至少在同一個網絡上有沒有代理等一起幹擾。您還將最終在發佈者和訂閱者之間實現緊密耦合。