Tuesday, November 30, 2010

Method overloading in WCF

Shout it kick it on DotNetKicks.com
Problem
I found scenario where I have to implement two method with the same name i.e Function overloading. But when I implement that I got error "System.InvalidOperationException"

System.InvalidOperationException: Cannot have two operations in the same 
contractwith the same name, methods GetData and GetData in type 
WcfServiceLibrary.IService1 violate this rule.



Solution
To resolve this issue you just need to use meaning full name for the method by using NAME field available in OperationContract attribute. So you need to give name to both or one of the method to avoid this problem. As you can see in below code that I did in control IService.cs interface

        [OperationContract(Name = "GetIntegerData")]
        string GetData(int value);

        [OperationContract(Name = "GetStringData")]
        string GetData(string value);


So after doing the change I get live service but the name of the method get change by the name specified in the  Name attribute which you can see in below image


So to consume service in my client application you need to use the method name you specified in the Name attribute. The code in my client application is

            ServiceReference1.Service1Client client = new Client.ServiceReference1.Service1Client();
            Console.WriteLine(client.GetIntegerData(5));
            Console.WriteLine(client.GetStringData("pranay"));

Summary
You can easily resolve issue of method over loading in WCF service with the help of Name field in OperationContract attribute.

1 comment:

  1. Do you have a spam problem on this blog; I also am a blogger, and I was wondering
    your situation; many of us have created some nice practices
    and we are looking to exchange strategies with others, please
    shoot me an email if interested.

    Here is my web site ... summer internship

    ReplyDelete