How to Overload Operation in WCF Service

Introduction

This blog gives you one trick of How to Overload Operation in WCF Service? Programming languages such as C++ and C# support method overloading: defining two methods with the same name but with different parameters. For example, this is a valid C# interface definition:

Example

interface IMOverload

{

    int Add(int arg1, int arg2);

    double Add(double arg1, double arg2);

}

However, operation overloading is invalid in the world of WSDL-based operations. Consequently, while the following contract definition compiles, it will throw an InvalidOperationException at the service host load time:
 

//Invalid contract definition:

[ServiceContract]

interface IMOverload

{

    [OperationContract]

    int Add(int arg1, int arg2);

    [OperationContract]

    double Add(double arg1, double arg2);

}

When you run the service this error will be occure.

However, you can manually enable operation overloading. The trick is using the Name property of the OperationContract attribute to alias the operation:
 

[AttributeUsage(AttributeTargets.Method)]

public sealed class OperationContractAttribute : Attribute

{

    public string Name

    { get; set; }

    //More members

}

 
You need to alias the operation both on the service and on the client side. On the service side, provide a unique name for the overloaded operations, as show below :
 

[ServiceContract]

public interface IMOverload

{

    // TODO: Add your service operations here

    //Here we used the trick of Name property of OperationContract

    [OperationContract(Name = "AddInt")]

    int Add(int arg1, int arg2);

 

    [OperationContract(Name = "AddDouble")]

    double Add(double arg1, double arg2);

}

 
Finally, use the Name property on the imported contract on the client side to alias and overload the methods, matching the imported operation names, as show below :
 

[ServiceContract]

public interface IMOverload

{

    // TODO: Add your service operations here

    //Here we used the trick of Name property of OperationContract

    [OperationContract(Name = "AddInt")]

    int Add(int arg1, int arg2);

    [OperationContract(Name = "AddDouble")]

    double Add(double arg1, double arg2);

}

public class MOverload : IMOverload

{

    public int Add(int arg1, int arg2)

    {

        return arg1 + arg2;

    }

    public double Add(double arg1, double arg2)

    {

        return arg1 + arg2;

    }

}

 
Now the client can benefit from the readable and smooth programming model offered by overloaded operations :
 

class Program

{

    static void Main(string[] args)

    {

        var proxy = new MOverloadClient();

        var res = proxy.AddInt(7, 5);

        var res2 = proxy.AddDouble(10.5, 1.5);

        Console.WriteLine("Result of Integer : " + res);

        Console.WriteLine("Result of Double : " + res2);

    }

}