Search code examples
c#wcfdatacontractoperationcontract

In WCF, is it better to have multiple operation contracts or to have only one operation with polymorphic data contract?


I was wondering if it was better in WCF to use multiple operation contracts or to have only one operation contract with a polymorphic data contract.

Let me give you a small example :

[OperationContract]
action1Answer action1(action1data a);

[OperationContract]
action2Answer action2(action2data a);

or

[OperationContract]
actionAnswer action(actionContract a);

Action contract would be an abstract class which both action1Contract and action2Contract will inherit from. The action contract would specify the do() member function in its interface which would have in turn to be overloaded in the child classes

Personnaly I find the second approach to be more intersting as it allow you to nicely encapsulate the data and the action in the derived actionContract and in turn makes it easier to add new actions. But It's the first time I'm using WCF so probably you know better!


Solution

  • This question borders on the edges of the Holy Wars of OO polymorphism and SOA, but I'll provide my two cents:

    When you're considering developing a service layer, it should be clear to the end consumer of the service what to pass in and what to expect; approach 2 doesn't handle that well. (Also, when doing SOAP with WCF and then loading from the wsdl in other .NET projects, it doesn't properly mark abstract classes, nor do interfaces get transferred. WSDLs have no way of describing a non-instantiable base class, it seems.)

    Though, I must admit, I think the second process is great using the KnownTypeAttributes (as I see just now marc_s has posted) - I've used it myself when allowing for unknown future requirements.