Method Overloading in WCF

WCF solves so many complex problems of the distributing computing, yet when it comes to simple things like overloading it fumbles. This is not what I say, but what I heard from some developers at my customer's site. So, I thought how can such a small thing could not be achievable in WCF when the underlying platform (.Net framework) support this by design.

After little thought, it is all clear why it does not work the same way it works with compiled languages. Its all the underlying protocols that makes it complex. But, it is not really tough to get this to work.

Here is the sample I worked on to get method overloading with WCF working like it does in C#.

Step 1: I've created a simple service contract with two methods using method overloading.

 [ServiceContract()]
public interface IMathService
{
    [OperationContract]
    int AddNumbers(int num1, int num2);
    [OperationContract]
    double AddNumbers(double num1, double num2);
}

Step 2: Tried to run the service and this is what I WCF told me...

image

Step 3: As WCF does not allow me to do this in a direct way, I looked at the OperationContract attribute to see if there is something that can help me. To my confidence, there is this property called Name. I've set this value to a unique value for both of these methods. now, the service contract looks like this:

 [ServiceContract()]
public interface IMathService
{
    [OperationContract(Name="AddIntegers")]
    int AddNumbers(int num1, int num2);
    [OperationContract(Name="AddDoubles")]
    double AddNumbers(double num1, double num2);
}

Step 4: Tried to run the service and this is what WCF told me now...

image

The problem seemed to be solved. And indeed it is, the generated proxy does not show any discrimination towards these methods. They'll be just like any other method (overloaded methods). Now its all over... Method overloading in WCF is very much possible and is very much simple.

I don't think I need to attach the source code as the only required change is already discussed here.

Note: If you are using WCF always think about messages and not methods. So, this situation should not end up in your design docs. If at all you end up here, you can use the approach suggested in this blog. Thanks Michael for pointing out this.