Apply WCF ServiceContract on Interface or Abstract class

wcf-interface-abstract
I had attended a technical session on “Windows Azure and Web Services” where a question was asked during the session “Can WCF ServiceContract attribute be applied on an Abstract class?” Generally we define this as an interface. The initial response was quite confusing but my thought and subsequent research cleared the understanding. Considering OOPS concept, there is nothing wrong implementing ServiceContract using an abstract class. C# compiler will never throw any compilation error if abstract class is used. I have put my understanding below with examples and request readers to put their comments also, which can help me to brainstorm and correct my understanding.
Lets start with a basic WCF code as mentioned in the example below

This will return value of 30. Now lets change interface to abstract class and see the implication, if any.

The above code compiles because there is nothing wrong in terms of concept and syntax. However running the console application gives the following exception
Unhandled Exception: System.InvalidOperationException: The service class of type SampleCalculator.Service.CalculatorService both defines a ServiceContract and inherits a ServiceContract from type SampleCalculator.Service.Calculator. Contract inheritance can only be used among interface types. If a class is marked with ServiceContractAttribute, then another service class cannot derive from it.
This exception tells us that service class cannot be derived from a class marked as ServiceContract attribute. And this is pretty logical. Imagine what would happen if a service is declared like this. When a client calls the Add method, should the Add method implemented in the abstract class get called or the one in the CalculatorService class. Please follow the below code for better understanding.

This test clearly shows that ServiceContract attribute should be applied on interface and not on abstract class that will be inherited by service class itself. However interface can be used as a ServiceContract and then inherit the abstract class from interface.

Leave a Reply