Broadcast to many webservices class
I want to make small framework with i could simply invoke webservices on many computers that have webservice.
So, i have i.e five computers with webservices. Each ws provides 2 functions (could be more, but this is example): DataFormat[] GetXData(int) Something[] GetYData(string, int).
Invoking service now looks like this: ServiceClient wsc; DataFormat[] data = wsc.GetXData(5);
I plan interface of framework like this:
MultiWebservice mws; DataFormat[] data = mws.BroadcastQuery( wsc.GetXData(5) );
As can see, i wish to inject function with iam interested to fire on every ws. And ret开发者_StackOverflowurn merged data (merging is not subject of post. i handle it myself)
I need a help how use C# to make this elegant, generic and if it isn't necessary, without many overloading of function because i don't want make new overloadings for each different return type or each function in ws.
Please, give me advice. Maybe this interface is wrong and could be better.
To give an answer similar to Thomas Li's, but using a generic type parameter for the methods, to allow any return type:
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));
}
}
Not sure if this helps but you can try tweaking this:
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); });
}
精彩评论