Oleg Shevchenko Oleg Shevchenko - 1 month ago 14
C# Question

How many contract types does WCF have?

I've recently faced with a question "How many contract types does WCF have". I know tree contract types:

ServiceContract
,
DataContract
,
OperationContract
, but I've been told that there are four. Could you please explain what other types of contracts WCF has?

Answer

There are four types of contract in WCF:

  1. Data Contract - it describes the format of your data and defines how data should be serialized/deserialized. To define a DataContract for you service, you can use DataContract, DataMember. See DataContract on MSDN

  2. Service Contract - it describes operations exposed by the service. It can also describe message exchange pattern. Service Contract can be defined using [ServiceContract] and [OperationContract] attributes. See ServiceContract on MSDN

  3. Message Contract - it gives us a control over a SOAP message. If you use just data contract, all the data will be in SOAP message body, but if you need a control/access to SOAP message header you can use MessageContract. Message contract can be applied to type using MessageContract attribute. Custom Header and Body can be included to message using MessageHeader and MessageBodyMember atttributes. See MessageContract on MSDN

  4. Fault Contract - it's a special contract for letting client know that something's wrong on service side. If an exception is thrown, it can't reach a client in the way it is. WCF handles it and conveys the error message to the client using SOAP Fault Contract. You can also define you one Fault Contract for an operation. You need to decorate your operation with [FaultContract(typeof(YouCustomFault))] and YouCustomFault with DataContract, DataMember attributes. See FaultContract on MSDN

And there is no such contract as OperationContract, it's just an attribute for defining a Service Contract operation.

Comments