Inheritance in WCF


As a WCF developer you always get question from interviewer : “Can we implement Inheritance in WCF ServiceContract?

Answer will be:

YES we can have Contract Inheritance in WCF. In other words in WCF one ServiceContract can inherit other ServiceContract.

Let us take an example which explain us how to achieve it.

You have a ServiceContract named IParentService as given below :


 [ServiceContract]
 public interface IParentService
 {
    [OperationContract]
    string ParentMessage(string message);
 }

Another ServiceContract named IChildService can inherit IParentService as following :


 [ServiceContract]
 public interface IChildService : IParentService
 {
   [OperationContract]
   string ChildMessage(string message);
 }

Next you need to decide on implemention of Service. Single Service class can implement both contract by implementing bottom most ServiceContract in hierarchy. In this case bottom most ServiceContract is IChildService Service can be implemented as following in a single service class:


 public class Service1 : IChildService
 {
   public string ChildMessage(string message)
   {
     return "Hello " + message + "from Child Service";
   }

   public string ParentMessage(string message)
   {
     return "Hello " + message + "from Parent Service";
   }
 }

Now you have choice that either you can expose whole hierarchy as single EndPoint or different EndPoints for different Service Contract. To expose contract hierarchy create EndPoint with bottom most ServiceContract. In this case we are creating EndPoint with Service Contract IChildService . At the client side operations from whole hierarchy could be invoked.

Hope this will help !!!

Jay Ganesh

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s