Friday, July 16, 2010

Method overloading in WCF service

Consider a scenario where we need to expose the service method GetAccount. The method can accept accountid in some cases or username or some other reference. One way to create this on wcf is to create different methods as GetAccountbyID, GetAccountByName etc. But creating overloading methods provides better way of handling it.

When we were using webservice, the only way to specify the alias name in webmethod attribute but the client app has to refer the service with alias name. So this doesn’t really qualify as overloaded method on client side but it’s an overloading method on the server side.

Sample overloaded method on webservice

[WebMethod(MessageName="GetAccountByID")]
public string GetAccount(int accountID)
{
//return account data
}






[WebMethod(MessageName="GetAccountByName")]
public string GetAccount (string userName)
{
//return account data
}

Now let’s see how we can do this with WCF service methods. Let’s consider the approach of webservice here. The WCF service would look like

My service interface would look like below

[OperationContract(Name = "GetAccountByID")]
string GetAccount(int value);


[OperationContract(Name = "GetAccountByName")]
string GetAccount(string userName);

and the service class will follow as

public string GetAccount(int value)
{
return string.Format("You entered: {0}", value);
}


public string GetAccount(string username)
{
return string.Format("You entered: {0}", username);
}


Lets refer this service on client side and see how we can consume it

As you can see, it is split as different methods on client side. So one thing clear here is that the method which is referred on the client side is referring to the name attribute defined on operationcontract.

No comments:

Post a Comment