Using multiple wcf services, factory class to return proxyclient
I have multiple services in my application. WebService1, WebService2,WebService3 and so on..
All the services have same methods, but they are hosted on different IPs.
Now when a client calls a methodA(1) then
WebService1Client.Method() should be called;
client calls a methodA(2) then WebService2Client.Method() should be called.
I do开发者_StackOverflow社区 not want to do a switch case for each and every function on the client.
I would rather prefer to create some class/methods which would return the appropriate proxyClient.
How can I create a class to return the object and further how to use that object.
Please point me to some sample codes or references.
Thanks
If all your services implement the same contract (I mean exactly the same, not a contract with the same methods), you can simply create proxies using the ChannelFactory class and cast the returned object into the contract interface.
This should give you the expected generic behavior.
One way to ensure the same interface is used all over is to put it into a separate class library and share it between all projects. Make sure you configure your service references to reuse types in referenced assemblies.
EDIT: This is how you would use the ChannelFactory, you can get rid of the service reference:
BasicHttpBinding myBinding = new BasicHttpBinding();
EndpointAddress myEndpoint = new EndpointAddress("http://localhost/MathService/Ep1");
ChannelFactory<IMath> myChannelFactory = new ChannelFactory<IMath>(myBinding, myEndpoint);
I am not quite sure why you want to wrap the creation of the proxies into a factory. The easiest usage pattern is to new the proxy where you need it and each time when you need. When you are not running reliable sessions or something other heavy stuff it does not have much overhead to new a proxy instance. On the other hand it makes sure that you have a connection that is working and that the channel is not in a faulted state.
When using the proxy you should make sure to close it when done and abort it when it throws an exception.
var proxy = new Proxy();
try { proxy.SomeMethod(); }
catch { proxy.Abort(); }
finally { proxy.Close(); }
精彩评论