Saturday, May 21, 2016

Wcf Service Name attribute

Concept of using services as an api, are very common, providing the advantage for different components/systems, to interact with each other in a loosely coupled manner. For this purpose, we can use asp.net web api or wcf services or wcf rest based services. So a service may have different methods as part of your system, which include methods like GetProductId, UpdateOrderById etc.

However, sharing the names of the methods will expose some kind of basic information of your system entities, as well. For example, like GetProductById clearly states that the there is an entity like Product in your system. Moreover, any method like GetCategoryProducts can be interpreted that there are two entities Product and Category in your system. Wouldn't it be nice to expose these methods using a different name. 

In wcf, we can do this through the use of the Name property, in the OperationContract attribute. Let's see how we can do this.
We will start by creating a wcf service with a method named GetData, which returns some data. So it will be like following:

   [ServiceContract]    
   public interface IService1    
   {    
       [OperationContract]    
       string GetData(int value);     
   }    
       
   public class Service1 : IService1    
   {    
      public string GetData(int value)    
      {    
          return string.Format("You entered: {0}", value);    
      }    
  }    

Next, we add a client application, add the reference to this project and call this method. So the code will look like the following:

   ServiceReference1.Service1Client _client = new ServiceReference1.Service1Client();  
   var _data = _client.GetData(2); 

Now in order to make this method to be called with another name, say GetMyData, we will add the Name property on the OperationContract attribute. So the code will change to following:

  [ServiceContract]  
    public interface IService1  
    {  
         [OperationContract(Name="GetMyData")]  
         string GetData(int value);  
    }  

Update the service reference and see that we cannot access the method with the same name again.

wcf service name attribute, Name attribute in Wcf Service

Similarly, we can add the Name property on the ServiceContract, DataContract and DataMember attributes.

Happy coding...!!! 

No comments:

Post a Comment