Can we implement Inheritance in WCF ServiceContract?
YES we can have Contract Inheritance in WCF. In other words in WCF one ServiceContract can inherit other ServiceContract.
Let us take an example that 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 implantation 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.
So at client side Service will be exposed as single class as given below,
In this way you can work with Inheritance in Service Contract. I hope you find this post useful. Thanks for reading.
Leave a Reply