2010-07-21 81 views
1

我通常会尝试将我的Web服务调用封装在我的客户端应用程序中。Properway封装异步Web服务通信

不是这样:

public Guid FindUserIDSelected(string userName) 
{ 
    MyWebServiceReference service = new MyWebServiceReference(GetEndpointBasedOnEnv(Env)); 
    return service.GetUserIDFromName(userName); 
} 

我有一个封装与Web服务通信的静态类。它通过确定环境(以及其他类似的东西)来处理端点解析。

所以上面的代码更改为如下所示:

public Guid FindUserIDSelected(string userName) 
{ 
    return Communication.GetUserIDFromName(userName); 
} 

但现在我有一个问题。 Silverlight只支持异步调用(至少就我所见)。所以调用Web服务,然后返回封装调用中的值不起作用。

我能想出的传递是在通信类用于已完成事件的委托最好的:

private Guid foundUserID; 

public void FindUserIDSelected(string userName) 
{ 
    Communication.GetUserIDFromName(userName, GetUserIDCompleted); 
} 

private void QuestionRecieved(object sender, GetUserIDFromNameCompletedEventArgs e) 
{ 
    foundUserID= e.Result(); 
} 

这有几个问题(在我看来)。

  1. 我现在的Web服务已经打破封装要素(完成的呼叫是真正的Web服务的回报。我不希望我的课的其余部分不得不关心服务)。
  2. 我不得不在课堂上暴露我的结果(foundUserID)。

我是不是太死板?这足够好吗?有没有更好的办法?

我是谁拥有这个问题的唯一一个?

回答

0

在我看来,它最好使用三项赛从您的通讯类,特别是如果你有一些东西一样[EventAggregator]1,这样你就可以过滤事件根据您的具体参数

下面是代码片段,这可能对您有所帮助。

公共静态类通信 {

public static event EventHandler<MyEventArgs> ServiceCallComplete; 

    public static void InvokeMyAcionComplete(MyEventArgs e) 
    { 
     EventHandler<MyEventArgs> handler = ServiceCallComplete; 
     if (handler != null) handler(null, e); 
    } 

    public static void CallService() 
    { 
     //Performed async call 

     // Fire the event to notify listeners 
     OnServiceCalled(); 
    } 

    private static void OnServiceCalled() 
    { 

     InvokeMyAcionComplete(new MyEventArgs()); 

    } 



} 

public class ClientCode 
{ 
     public void CallService() 
     { 
      Communication.CallService(); 

      //Subscribe to the event and get notified when the call is complete 
      Communication.ServiceCallComplete += OnServiceCalled; 
     } 

    private void OnServiceCalled(object sender, MyEventArgs e) 
    { 
      //MyEventArgs is your customized event argument 

      //Do something with the result 
    } 
} 

希望这有助于