簡體   English   中英

廣播到許多Web服務類

[英]Broadcast to many webservices class

我想制作一個小型框架,我可以簡單地在具有Web服務的許多計算機上調用Web服務。

因此,我有5台帶有Web服務的計算機。 每個ws提供2個函數(可能更多,但這是示例):DataFormat [] GetXData(int)Something [] GetYData(string,int)。

現在調用服務如下所示:ServiceClient wsc; DataFormat [] data = wsc.GetXData(5);

我計划這樣的框架接口:

MultiWebservice mws; DataFormat [] data = mws.BroadcastQuery(wsc.GetXData(5));

可以看到,我希望向有興趣在每個ws上觸發的iam注入函數。 然后返回合並的數據(合並不是發布的主題。我自己處理)

我需要一個幫助,如何使用C#來使此優雅,通用,並且如果沒有必要,而又沒有很多函數的重載,因為我不想為每種不同的返回類型或ws中的每個函數都進行新的重載。

請給我建議。 也許這個接口是錯誤的,可能會更好。

不確定這是否有幫助,但您可以嘗試進行以下調整:

public class WebServiceClient
{
    public int[] GetXData(int intVar)
    {
        return new int[] { intVar, intVar };
    }
}

public class BoardcastingWebServiceCleint
{
    public int[] BroadcastQuery(Func<WebServiceClient, int[]> webServiceCall)
    {
        List<WebServiceClient> clients = new List<WebServiceClient>();
        List<int> allResults = new List<int>();
        foreach (WebServiceClient client in clients)
        {
            int[] result = webServiceCall.Invoke(client);
            allResults.AddRange(result);
        }

        return allResults.ToArray();
    }
}

static void Main(string[] args)
{
    BoardcastingWebServiceCleint bwsc = new BoardcastingWebServiceCleint();
    bwsc.BroadcastQuery((client) => { return client.GetXData(5); });
}

要給出類似於托馬斯·李的答案,但使用通用類型參數作為方法,以允許任何返回類型:

 public class WSClient {
      public int GetPower (int var) { return var * var; }
      public int[] GetDuplicatePowers (int var) {
              return new[] { GetPower(var), GetPower (var) };
      }
 }

 public class Multiplexer<T> {
      IList<T> _sources;
      public Multiplexer (IEnumerable<T> sources) {
             _sources = new List<T> (sources);
      }

      public IEnumerable<TResult> Call<TResult> (Func<T, TResult> func) {
          return _sources.Select (s => func(s));
      }

      public IEnumerable<TResult> AggregateCall<TResult> (Func<T, IEnumerable<TResult>> func) {
          return _sources.SelectMany (s => func(s));
      }
 }

 public class Test {
     public static void Main (string[] args) {
           var m = new Multiplexer<WSClient> (new[] { new WSClient (), new WSClient () });
           var powers = m.Call (c => c.GetPower (2));
           var agg_powers = m.AggregateCall (c => c.GetDuplicatePowers (2));
     }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM