views:

133

answers:

2

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!

+1  A: 

I agree approach #2 looks better - from an OOP standpoint.

But: SOA/WCF and polymorphism typically don't match too well - SOA (at least when doing SOAP based calls) needs concrete classes that can be expressed in the WSDL/XSD that defines your service.

You can use derived datatypes based on a common base type - if you do, you'll have to look into the KnownType attribute (or ServiceKnownType) to signal to WCF that you might be returning something else than the operation contract actually says it will.

marc_s
+2  A: 

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.

mattdekrey
Thanks for the very informative reply! I never realized OO and SOA could be in contradiction like this. Even though I prefer the second approach (comming from a OO backgroud), I might go with the first one, for the sake of service description.
Gab Royer
I'm currently reading "Microsoft .NET: Architecting Applications for the Enterprise", which discusses SOA to a good length, but it refers to Martin Fowler's "Patterns of Enterprise Application Architecture" quite a bit; both should be a great read if you're interested.
mattdekrey
Thanks for the heads up
Gab Royer