Operation Overloading in WCF

Operation Overloading in WCF

Programming such C++ and C# support method overloading; that is, defining two methods with the same name but with different paramaters.

interface IUser

{

    int AddUser(string UserName, string password);

    int AddUser(string UserName, string password, string EmailID);

}

 

This is a valid interface in C#.

However, operation overloading is invalid in WSDL based operations, since all operations must have unique names (they are identified by name in the messages).

[ServiceContract]

interface IUser

{

   [OperationContract]

   int AddUser(string UserName, string password);

 

   [OperationContract] 

   int AddUser(string UserName, string password, string EmailID);

}

This contract definition is invalid and it will throw an InvalidOperationException at the service host load time.

 

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

}

 

Alias the operation both on the service and on the client side. On the service side, provide a unique name for each overloaded operation.

[ServiceContract]

interface IUser

{

    [OperationContract(Name= "AddUser")]

    int Add(string UserName, string password);

 

    [OperationContract(Name = "AddUserWithEmail")]

    int Add(string UserName, string password, string EmailID);

}

 

When the client imports the contract and generates the proxy, the imported operations will have the aliased name.

[ServiceContract]

interface IUser

{

    [OperationContract]

    int AddUser(string UserName, string password);

 

    [OperationContract]

    int AddUserWithEmail(string UserName, string password, string EmailID);

}

 

class UserClient : ClientBase<IUser>, IUser

{

    public int AddUser(string arg1, string arg2)

    {

        return Channel.AddUser (arg1, arg2);

    }

    public int AddUserWithEmail(string arg1, string arg2 , string arg3)

    {

        return Channel.AddUserWithEmail(string arg1, string arg2, string arg3);

    }

    //Rest of the proxy

}